a
    h+1                 	   @   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
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+m,Z, ddl-m.Z.m/Z/m0Z0 e'1e2Z3ee%ddG dd de#Z4G dd dej5Z6dCej5e	j7e	j7e	j7ee	j7 e8e8dddZ9G dd dej5Z:G d d! d!ej5Z;G d"d# d#eZ<e%G d$d% d%eZ=G d&d' d'ej5Z>G d(d) d)e=Z?G d*d+ d+ej5Z@G d,d- d-ej5ZAG d.d/ d/ej5ZBG d0d1 d1ej5ZCG d2d3 d3ej5ZDG d4d5 d5eZEG d6d7 d7ej5ZFG d8d9 d9ej5ZGG d:d; d;e=ZHe%d<dG d=d> d>e=ZIe%d?dG d@dA dAe=eZJg dBZKdS )Dz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   )	AutoModelAutoModelForCausalLMAutoModelForSeq2SeqLM   )InstructBlipConfigInstructBlipQFormerConfigInstructBlipVisionConfigzQ
    Class defining the outputs of [`InstructBlipForConditionalGeneration`].
    )Z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< ee d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 r/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/instructblip/modeling_instructblip.py	<genexpr>J   s   
zKInstructBlipForConditionalGenerationModelOutput.to_tuple.<locals>.<genexpr>)tuplekeysr2   r4   r2   r5   r/   I   s    z8InstructBlipForConditionalGenerationModelOutput.to_tuple)__name__
__module____qualname____doc__r&   r   r7   torchFloatTensor__annotations__r'   r(   r)   r*   r   r/   r4   r4   r4   r5   r%   .   s   
r%   c                       sR   e Zd Zed fddZejeeejdddZdej	e
ejd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   )Zin_channelsZout_channelsZkernel_sizeZstrider   )super__init__rB   hidden_size	embed_dimZ
image_size
patch_sizer   	Parameterr=   Zrandnclass_embeddingConv2dpatch_embeddingnum_patchesnum_positionsposition_embeddingr3   rB   	__class__r4   r5   rD   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   ZbicubicF)sizemodeZalign_cornersdim)shaperN   r=   Zjit
is_tracingrG   r   reshapepermuter   
functionalZinterpolateviewcat)r3   rR   rS   rT   rL   rM   Zclass_pos_embedZpatch_pos_embedrY   Z
new_heightZ	new_widthZsqrt_num_positionsr4   r4   r5   interpolate_pos_encodingf   s(    



z5InstructBlipVisionEmbeddings.interpolate_pos_encodingF)pixel_valuesra   r,   c                 C   s   |j \}}}}| jjj}| |j|d}|ddd}| j|dd|}	t	j
|	|gdd}
|rx| |
||}n| j}|
|d d d |
dd d f | }
|
S )Ndtyper   r!   rU   rX   )rZ   rK   weightrd   toflatten	transposerI   expandr=   r`   ra   rN   rV   )r3   rb   ra   
batch_size_rS   rT   Ztarget_dtypeZpatch_embedsZclass_embedsrR   rN   r4   r4   r5   forward   s    
*z$InstructBlipVisionEmbeddings.forward)F)r9   r:   r;   r$   rD   r=   Tensorintra   r>   boolrl   __classcell__r4   r4   rP   r5   r@   S   s   (r@           )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 )NrU   rX   )ptrainingr!   r   )	r=   matmulrh   r   r^   Zsoftmaxrx   r{   
contiguous)
rr   rs   rt   ru   rv   rw   rx   kwargsattn_weightsattn_outputr4   r4   r5   eager_attention_forward   s    
r   c                
       sr   e Zd ZdZ fddZejeedddZdeje	ej e	e
 eeje	ej e	eej  f d	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rZtd| j d| j d| jd | _	d| _
|j| _tj| jd| j dd| _|jrtt| j}tt| j}nd }d }|d urt|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)Zrequires_grad)rC   rD   rB   rE   rF   num_attention_heads	num_headshead_dim
ValueErrorscaleZ	is_causalattention_dropoutr   Linearqkvqkv_biasrH   r=   zerosr`   Z
zeros_liker   
projection)r3   rB   Zq_biasZv_biasr   rP   r4   r5   rD      s0    

zInstructBlipAttention.__init__)tensorseq_lenbszc                 C   s    | ||| j| jdd S )Nr!   r   )r_   r   r   rh   r}   )r3   r   r   r   r4   r4   r5   _shape   s    zInstructBlipAttention._shapeNF)hidden_states	head_maskoutput_attentionsr,   c                 K   s   |  \}}}| |}|||d| j|| j ddddd}|d |d |d   }	}
}t}| jjdkr| jjdkr|rt	d nt
| jj }|| |	|
|fd	| jsd
n| j| jd|\}}|||d }| |}|r||fn|d	f}|S )z#Input shape: Batch x Time x Channelr   r   r   r!      eagerZsdpaz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.Nrq   )rv   rx   rw   rU   )rV   r   r\   r   r]   r   rB   Z_attn_implementationloggerZwarning_oncer   r{   r   r   r}   r   )r3   r   r   r   r~   r   Ztgt_lenrF   Z	mixed_qkvZquery_statesZ
key_statesZvalue_statesZattention_interfacer   r   outputsr4   r4   r5   rl      s:    	



zInstructBlipAttention.forward)NF)r9   r:   r;   r<   rD   r=   rm   rn   r   r   ro   r7   rl   rp   r4   r4   rP   r5   r      s     r   c                       s0   e Zd Z fddZejejdddZ  ZS )InstructBlipMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S N)rC   rD   rB   r	   
hidden_actactivation_fnr   r   rE   intermediate_sizefc1fc2rO   rP   r4   r5   rD     s
    
zInstructBlipMLP.__init__r   r,   c                 C   s"   |  |}| |}| |}|S r   )r   r   r   r3   r   r4   r4   r5   rl     s    


zInstructBlipMLP.forwardr9   r:   r;   rD   r=   rm   rl   rp   r4   r4   rP   r5   r     s   r   c                       sF   e Zd Zed fddZdejejee e	ej
 dddZ  ZS )	InstructBlipEncoderLayerrA   c                    sR   t    |j| _t|| _tj| j|jd| _	t
|| _tj| j|jd| _d S Neps)rC   rD   rE   rF   r   	self_attnr   	LayerNormlayer_norm_epslayer_norm1r   mlplayer_norm2rO   rP   r4   r5   rD     s    


z!InstructBlipEncoderLayer.__init__F)r   rv   r   r,   c                 C   sb   |}|  |}| j|||d\}}|| }|}| |}| |}|| }|f}|r^||f7 }|S )aI  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
                `(config.encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r   r   r   )r   r   r   r   )r3   r   rv   r   Zresidualr   r   r4   r4   r5   rl   $  s     




z InstructBlipEncoderLayer.forward)F)r9   r:   r;   r"   rD   r=   rm   r   ro   r7   r>   rl   rp   r4   r4   rP   r5   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 )InstructBlipPreTrainedModelrB   ZblipT)InstructBlipQFormerEmbeddingsr   %InstructBlipQFormerMultiHeadAttentionInstructBlipQFormerSelfOutputc                 C   s   | j j}t|tjtjfrD|jjjd|d |j	dur|j	j
  nt|tjrd|jjjd|d nvt|tjr|j	j
  |jjd nNt|trtjj|jd|d tjj|jd|d nt|ttfr|jj
  dS )zInitialize the weightsrq   )meanZstdN      ?)rB   Zinitializer_range
isinstancer   r   rJ   re   dataZnormal_r   Zzero_	Embeddingr   Zfill_r@   initZtrunc_normal_rN   rI   $InstructBlipForConditionalGenerationInstructBlipModelquery_tokens)r3   rr   factorr4   r4   r5   _init_weights^  s    

z)InstructBlipPreTrainedModel._init_weightsN)r9   r:   r;   r"   r?   Zbase_model_prefixZsupports_gradient_checkpointing_supports_attention_backend_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_no_split_modulesr   r4   r4   r4   r5   r   K  s   
r   c                       sX   e Zd ZdZed fddZd	eej ee	 ee	 ee	 e
eef d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`.
    rA   c                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r4   )r   )r0   rk   rA   r4   r5   
<listcomp>      z0InstructBlipEncoder.__init__.<locals>.<listcomp>F)	rC   rD   rB   r   
ModuleListrangenum_hidden_layerslayersgradient_checkpointingrO   rP   rA   r5   rD   }  s    
 zInstructBlipEncoder.__init__N)rv   r   output_hidden_statesreturn_dictr,   c                 C   s   |dur|n| j j}|dur |n| j j}|dur4|n| j j}|rDdnd}|rPdnd}|}t| jD ]>\}	}
|rx||f }|
|||d}|d }|rb||d f }qb|r||f }|stdd |||fD S t|||dS )	a  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Embedded representation of the inputs. Should be float, not int tokens.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

                [What are attention masks?](../glossary#attention-mask)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        Nr4   )rv   r   r   r!   c                 s   s   | ]}|d ur|V  qd S r   r4   r0   vr4   r4   r5   r6     r   z.InstructBlipEncoder.forward.<locals>.<genexpr>)last_hidden_stater   
attentions)rB   r   r   use_return_dict	enumerater   r7   r   )r3   inputs_embedsrv   r   r   r   Zencoder_statesZall_attentionsr   idxZencoder_layerlayer_outputsr4   r4   r5   rl     s2    

zInstructBlipEncoder.forward)NNNN)r9   r:   r;   r<   r"   rD   r   r=   rm   ro   r   r7   r   rl   rp   r4   r4   rP   r5   r   s  s   		    
r   c                
       sp   e Zd ZU dZeed< ed fddZedee	j
 ee ee ee eeeef dd	d
Zdd Z  ZS )InstructBlipVisionModelrb   rB   rA   c                    sJ   t  | || _|j}t|| _t|| _tj	||j
d| _|   d S r   )rC   rD   rB   rE   r@   rR   r   encoderr   r   r   post_layernorm	post_init)r3   rB   rF   rP   r4   r5   rD     s    

z InstructBlipVisionModel.__init__NF)rb   r   r   r   ra   r,   c           
      C   s   |d ur|n| j j}|d ur |n| j j}|d ur4|n| j j}|d u rLtd| j||d}| j||||d}|d }| |}|d d dd d f }	| |	}	|s||	f|dd   S t||	|j	|j
dS )Nz You have to specify pixel_values)ra   )r   r   r   r   r   r!   )r   pooler_outputr   r   )rB   r   r   r   r   rR   r   r   r   r   r   )
r3   rb   r   r   r   ra   r   encoder_outputsr   pooled_outputr4   r4   r5   rl     s2    	

zInstructBlipVisionModel.forwardc                 C   s   | j S r   )rR   r2   r4   r4   r5   get_input_embeddings  s    z,InstructBlipVisionModel.get_input_embeddings)NNNNF)r9   r:   r;   main_input_namer$   r?   rD   r   r   r=   r>   ro   r   r7   r   rl   r   rp   r4   r4   rP   r5   r     s$   
     
*r   c                       sP   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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	| _|rt
|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   Z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)rC   rD   rB   rE   r   hasattrr   rn   attention_head_sizeall_head_sizer   r   rs   Zencoder_hidden_sizert   ru   DropoutZattention_probs_dropout_probrx   r.   r   max_position_embeddingsr   distance_embeddingsave_attentionr3   rB   is_cross_attentionrP   r4   r5   rD     s.    

z.InstructBlipQFormerMultiHeadAttention.__init__c                 C   s
   || _ d S r   attn_gradients)r3   r   r4   r4   r5   save_attn_gradients  s    z9InstructBlipQFormerMultiHeadAttention.save_attn_gradientsc                 C   s   | j S r   r   r2   r4   r4   r5   get_attn_gradients!  s    z8InstructBlipQFormerMultiHeadAttention.get_attn_gradientsc                 C   s
   || _ d S r   attention_map)r3   r   r4   r4   r5   save_attention_map$  s    z8InstructBlipQFormerMultiHeadAttention.save_attention_mapc                 C   s   | j S r   r   r2   r4   r4   r5   get_attention_map'  s    z7InstructBlipQFormerMultiHeadAttention.get_attention_mapc                 C   s6   |  d d | j| jf }|j| }|ddddS )NrU   r   r   r!   r   )rV   r   r   r_   r]   )r3   xZnew_x_shaper4   r4   r5   transpose_for_scores*  s    
z:InstructBlipQFormerMultiHeadAttention.transpose_for_scoresNc                 C   s.  |d u}|r2|  | |}|  | |}	|}n |  | |}|  | |}	| |}
|  |
}t||dd}| jdks| jdkrV| 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r"td||}|| }n4| jdkrVt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| }|r$||fn|f}|S )NrU   ry   r   r   r!   rd   devicerc   zbhld,lrd->bhlrzbhrd,lrd->bhlrrX   r   r   r   )r   rt   ru   rs   r=   r|   rh   r   rV   arangelongr   r_   r   r   rf   rd   Zeinsummathsqrtr   r   ZSoftmaxr   r   register_hookr   rx   r]   r}   r   )r3   r   rv   r   encoder_hidden_statesencoder_attention_maskr   r   Z	key_layerZvalue_layerZmixed_query_layerZquery_layerZattention_scores
seq_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_scores_dtypeZattention_probsZattention_probs_droppedZcontext_layerZnew_context_layer_shaper   r4   r4   r5   rl   /  sR    







z-InstructBlipQFormerMultiHeadAttention.forward)F)NNNNF)r9   r:   r;   rD   r   r   r   r   r   rl   rp   r4   r4   rP   r5   r     s        r   c                       s4   e Zd Z fddZejejejdddZ  ZS )r   c                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S r   )rC   rD   r   r   rE   denser   r   r   hidden_dropout_probrx   rO   rP   r4   r5   rD     s    
z&InstructBlipQFormerSelfOutput.__init__r   input_tensorr,   c                 C   s&   |  |}| |}| || }|S r   r   rx   r   r3   r   r  r4   r4   r5   rl     s    

z%InstructBlipQFormerSelfOutput.forwardr   r4   r4   rP   r5   r   ~  s   r   c                	       sf   e Zd Zd
 fdd	Zdd Zdejeej eej eej eej ee	 e
ej ddd	Z  ZS )InstructBlipQFormerAttentionFc                    s,   t    t||| _t|| _t | _d S r   )rC   rD   r   	attentionr   outputsetpruned_headsr   rP   r4   r5   rD     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!   rX   )lenr   r  r   r   r
  r   rs   rt   ru   r  r   r   union)r3   headsindexr4   r4   r5   prune_heads  s    z(InstructBlipQFormerAttention.prune_headsN)r   rv   r   r   r   r   r,   c           
      C   s<   | j ||||||d}| |d |}|f|dd   }	|	S )N)r   rv   r   r   r   r   r   r!   )r  r  )
r3   r   rv   r   r   r   r   Zself_outputsattention_outputr   r4   r4   r5   rl     s    	z$InstructBlipQFormerAttention.forward)F)NNNNF)r9   r:   r;   rD   r  r=   rm   r   r>   ro   r7   rl   rp   r4   r4   rP   r5   r    s         r  c                       s0   e Zd Z fddZejejdddZ  ZS )InstructBlipQFormerIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )rC   rD   r   r   rE   r   r   r   r   strr	   intermediate_act_fnrO   rP   r4   r5   rD     s
    
z(InstructBlipQFormerIntermediate.__init__r   c                 C   s   |  |}| |}|S r   )r   r  r   r4   r4   r5   rl     s    

z'InstructBlipQFormerIntermediate.forwardr   r4   r4   rP   r5   r    s   r  c                       s4   e Zd Z fddZejejejdddZ  ZS )InstructBlipQFormerOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )rC   rD   r   r   r   rE   r   r   r   r   r  rx   rO   rP   r4   r5   rD     s    
z"InstructBlipQFormerOutput.__init__r  c                 C   s&   |  |}| |}| || }|S r   r  r  r4   r4   r5   rl     s    

z!InstructBlipQFormerOutput.forwardr   r4   r4   rP   r5   r    s   r  c                       s6   e Zd Z fddZdddZdd	 Zd
d Z  ZS )InstructBlipQFormerLayerc                    s~   t    |j| _d| _t|| _|| _||j dkrLt|dd| _d| _	nd| _	t
|| _t|| _t
|| _t|| _d S )Nr!   r   T)r   F)rC   rD   chunk_size_feed_forwardseq_len_dimr  r  	layer_idxZcross_attention_frequencycrossattentionhas_cross_attentionr  intermediater  r  intermediate_queryoutput_query)r3   rB   r  rP   r4   r5   rD     s    




z!InstructBlipQFormerLayer.__init__NFr   c              	   C   s  | j ||||d}|d }	|dd  }
|dkr|	d d d |d d f }| jr|d u r^td| j||||||d}|d }|
|dd   }
t| j| j| j|}|	jd |krt| j	| j| j|	d d |d d d f 
|j}tj||gdd}nt| j	| j| j|	}|f|
 }
|
S )N)rv   r   r   r   r!   z>encoder_hidden_states must be given for cross-attention layers)rv   r   r   r   r   rX   )r  r  r   r  r   feed_forward_chunk_queryr  r  rZ   feed_forward_chunkrf   r   r=   r`   )r3   r   rv   r   r   r   r   query_lengthZself_attention_outputsr  r   Zquery_attention_outputZcross_attention_outputslayer_outputZlayer_output_textr4   r4   r5   rl     s^    

z InstructBlipQFormerLayer.forwardc                 C   s   |  |}| ||}|S r   )r  r  r3   r  Zintermediate_outputr!  r4   r4   r5   r  /  s    
z+InstructBlipQFormerLayer.feed_forward_chunkc                 C   s   |  |}| ||}|S r   )r  r  r"  r4   r4   r5   r  4  s    
z1InstructBlipQFormerLayer.feed_forward_chunk_query)NNNNFr   )r9   r:   r;   rD   rl   r  r  rp   r4   r4   rP   r5   r    s         
?r  c                       s&   e Zd Z fddZd	ddZ  ZS )
InstructBlipQFormerEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  |qS r4   )r  )r0   r  rA   r4   r5   r   @  r   z7InstructBlipQFormerEncoder.__init__.<locals>.<listcomp>F)	rC   rD   rB   r   r   r   r   layerr   rO   rP   rA   r5   rD   <  s    
z#InstructBlipQFormerEncoder.__init__NFTr   c
              
   C   s   |rdnd }
|rdnd }|r dnd }t | jjD ]|}| j| }|rL|
|f }
|d ur\|| nd }||||||||	d}|d }|r0||d f }|	dkr0|jr0||d f }q0|r|
|f }
|stdd ||
||fD S t||
||dS )	Nr4   )r   r   r   r   r!   r   c                 s   s   | ]}|d ur|V  qd S r   r4   r   r4   r4   r5   r6   o  s   z5InstructBlipQFormerEncoder.forward.<locals>.<genexpr>)r   r   r   cross_attentions)r   rB   r   r$  r  r7   r   )r3   r   rv   r   r   r   r   r   r   r   Zall_hidden_statesZall_self_attentionsZall_cross_attentionsiZlayer_moduleZlayer_head_maskr   r4   r4   r5   rl   D  sL    




z"InstructBlipQFormerEncoder.forward)NNNNFFTr   )r9   r:   r;   rD   rl   rp   r4   r4   rP   r5   r#  ;  s           r#  c                       s*   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)Zpadding_idxr   position_ids)r!   rU   F)
persistentr   r   )rC   rD   r   r   
vocab_sizerE   Zpad_token_idword_embeddingsr   position_embeddingsr   r   	layernormr   r  rx   Zregister_bufferr=   r   ri   r.   r   rB   rO   rP   r4   r5   rD     s    
z&InstructBlipQFormerEmbeddings.__init__Nr   c                 C   s   |d ur|  d }nd}|d u r@| jd d ||| f  }|d ur| |}| jdkrv| ||j}|| }|d urtj	||fdd}n|}|| j
jj}| 
|}| |}|S )Nr!   r   r   rX   )rV   r'  cloner*  r   r+  rf   r   r=   r`   r,  re   rd   rx   )r3   	input_idsr'  query_embedsZpast_key_values_lengthr   rR   r+  r4   r4   r5   rl     s"    



z%InstructBlipQFormerEmbeddings.forward)NNNr   )r9   r:   r;   r<   rD   rl   rp   r4   r4   rP   r5   r     s       r   c                       s   e Zd ZdZdZdZdZdZed fddZ	dd Z
dd	 Zd
d Zdejee ejeejdddZdejeej eej eej eej eej eej ee ee ee eeej ef d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.
    FrA   c                    s2   t  | || _t|| _t|| _|   d S r   )rC   rD   rB   r   rR   r#  r   r   rO   rP   r4   r5   rD     s
    

z!InstructBlipQFormerModel.__init__c                 C   s   | j jS r   rR   r*  r2   r4   r4   r5   r     s    z-InstructBlipQFormerModel.get_input_embeddingsc                 C   s   || j _d S r   r1  r3   ru   r4   r4   r5   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   r$  r  r  )r3   Zheads_to_pruner$  r  r4   r4   r5   _prune_heads  s    z%InstructBlipQFormerModel._prune_heads)rv   input_shaper   	has_queryr,   c                 C   s   |  dkr*|dddddddf }n>|  dkrP|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 )rc   r   g     )rY   r   rZ   rf   rd   )r3   rv   r6  r   r7  extended_attention_maskr4   r4   r5   get_extended_attention_mask  s    	z4InstructBlipQFormerModel.get_extended_attention_maskN)r.  rv   r'  r/  r   r   r   r   r   r   r,   c                    s  |dur|n j j}|	dur |	n j j}	|
dur4|
n j j}
|du rT|du rTtd|durf|jd nd} j|||d}| dd }|\}}|j}|du rt	j
||f|d} |||}|durNt|tr|d  \}}}n| \}}}||f}t|tr fdd	|D }n.|du rBt	j
||d} |}n
 |}nd} | j j} j|||||||	|
|d
	}|d }|dddddf }|
s||f|dd  S t|||j|j|j|jdS )a  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *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` of shape `(batch_size, sequence_length)`, *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` of length `config.n_layers` with each tuple having 4 tensors of:
            shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): 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`).
        Nz7You have to specify query_embeds when input_ids is Noner!   r   )r.  r'  r/  rU   )r   c                    s   g | ]}  |qS r4   )invert_attention_mask)r0   maskr2   r4   r5   r   H  r   z4InstructBlipQFormerModel.forward.<locals>.<listcomp>)rv   r   r   r   r   r   r   r   )r   r   past_key_valuesr   r   r%  )rB   r   r   r   r   rZ   rR   rV   r   r=   onesr:  r   listr;  Zget_head_maskr   r   r   r=  r   r   r%  )r3   r.  rv   r'  r/  r   r   r   r   r   r   r   Zembedding_outputr6  rj   r   r   r9  Zencoder_batch_sizeZencoder_sequence_lengthrk   Zencoder_hidden_shapeZencoder_extended_attention_maskr   Zsequence_outputr   r4   r2   r5   rl     sl     


z InstructBlipQFormerModel.forward)F)	NNNNNNNNN)r9   r:   r;   r<   r   r   r   r   r#   rD   r   r3  r5  r=   rm   r7   rn   r   ro   r:  
LongTensorr   r>   r   r   rl   rp   r4   r4   rP   r5   r0    sN   
 .         r0  z[
    InstructBLIP base Model consisting of language model, qformer and vision encoder.
    c                       s   e Zd ZdZdgZed fddZdd Zdd	 Zd
d Z	dd Z
ejejdddZeedejejeej eej eej eej eej eej ee ee ee eee ee eeef dddZ  ZS )r   rb   r   rA   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r| j| jj |   d S Nr!   )rC   rD   r   vision_configvision_modelr   rH   r=   r   num_query_tokensqformer_configrE   r   r0  qformerr   text_configlanguage_projectionr   from_configlanguage_modelr   extend_keep_in_fp32_modulesr   rO   rP   r4   r5   rD   |  s    zInstructBlipModel.__init__c                 C   s
   | j  S r   rJ  r   r2   r4   r4   r5   r     s    z&InstructBlipModel.get_input_embeddingsc                 C   s   | j | d S r   rJ  r3  r2  r4   r4   r5   r3    s    z&InstructBlipModel.set_input_embeddingsc                 C   s(   | j js$| jj| jj_| jj| jj_d S r   rB   use_decoder_only_language_modelrJ  Zsharedr   Zembed_tokensdecoderr2   r4   r4   r5   _tie_weights  s    zInstructBlipModel._tie_weightsc                 C   sL   | j }t|dkr2d|vr2tj dkr2td t| jdrHd| jj	_
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!   rJ  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_mapr  r=   cudaZdevice_countr   warningr   rJ  rT  Zio_same_devicer3   rV  r4   r4   r5   _preprocess_accelerate  s    "z(InstructBlipModel._preprocess_accelerater.  r   c                 C   s`   |du r8||   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   rU   r   r=   r   rB   Zimage_token_idr   r   allZ	unsqueezeZ	expand_asrf   r3   r.  r   special_image_maskr4   r4   r5   get_placeholder_mask  s    z&InstructBlipModel.get_placeholder_maskNF)rb   qformer_input_idsqformer_attention_maskr.  rv   decoder_input_idsdecoder_attention_maskr   r   r   r   ra   	use_cacher~   r,   c                 K   s  |dur|n| j j}| j||	|
||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 rt|}tj||gdd}| j||||||	|
|d}|d ddd|dddf }|du r| j |}|du rt|}| |}||j|j}| j||d	}|||}| j jrr| jf |||	|
||d
|}n"| jf |||||	|
||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)
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
            provided to serve as text prompt, which the language model can continue.

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

            [What are input IDs?](../glossary#input-ids)
        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.
        N)rb   r   r   r   ra   r   rU   r   r!   rX   )r.  rv   r/  r   r   r   r   r   r   r   rv   r   r   r   rf  )r   rv   rd  re  r   r   r   rf  r-   )rB   r   rC  r=   r>  rV   r   r   r   ri   rZ   	ones_liker`   rF  rJ  r   rH  rf   rd   ra  masked_scatterrP  r%   )r3   rb   rb  rc  r.  rv   rd  re  r   r   r   r   ra   rf  r~   r(   image_embedsimage_attention_maskr   query_attention_maskquery_outputsquery_outputlanguage_model_inputsr`  r   r4   r4   r5   rl     s|    1  

$





	zInstructBlipModel.forward)NNNNNNNNNFN)r9   r:   r;   r   rL  r"   rD   r   r3  rR  rZ  r=   r@  r>   ra  r   r   r   rm   ro   r   r   r   r7   r%   rl   rp   r4   r4   rP   r5   r   s  sL              
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ed fddZdd	 Z	d
d Z
dd ZejdddZdd Zdd Zdd Zdd Zd'ejejeej ee ee dddZejejddd Zeed(ejejeej eej eej eej eej eej ee ee eej ee eee ee eee f d!d"d#Z!e" d)ejeej eej eej eej eej eejd$d%d&Z#  Z$S )*r   rB   rb   Tr   rA   c                    s   t  | t|j| _tt	d|j
|jj| _t|j| _t|jj|jj| _|jrnt|j}nt|j}|jd ur| j|j |jd ur| j|j || _|   d S rA  )rC   rD   r   _from_configrB  rC  r   rH   r=   r   rD  rE  rE   r   r0  rF  r   rG  rH  rP  r   rI  r    r   rK  rL  rJ  r   )r3   rB   rJ  rP   r4   r5   rD   I  s    

z-InstructBlipForConditionalGeneration.__init__c                 C   s
   | j  S r   rM  r2   r4   r4   r5   r   c  s    z9InstructBlipForConditionalGeneration.get_input_embeddingsc                 C   s   | j | d S r   rN  r2  r4   r4   r5   r3  f  s    z9InstructBlipForConditionalGeneration.set_input_embeddingsc                 C   s   | j | d S r   )rJ  set_output_embeddings)r3   Znew_embeddingsr4   r4   r5   rr  i  s    z:InstructBlipForConditionalGeneration.set_output_embeddingsr+   c                 C   s
   | j  S r   )rJ  get_output_embeddingsr2   r4   r4   r5   rs  l  s    z:InstructBlipForConditionalGeneration.get_output_embeddingsc                 C   s
   | j  S r   )rJ  get_encoderr2   r4   r4   r5   rt  o  s    z0InstructBlipForConditionalGeneration.get_encoderc                 C   s
   | j  S r   )rJ  get_decoderr2   r4   r4   r5   ru  r  s    z0InstructBlipForConditionalGeneration.get_decoderc                 C   s(   | j js$| jj| jj_| jj| jj_d S r   rO  r2   r4   r4   r5   rR  v  s    z1InstructBlipForConditionalGeneration._tie_weightsc                 C   sL   | j }t|dkr2d|vr2tj dkr2td t| jdrHd| jj	_
dS rS  rU  rY  r4   r4   r5   rZ  |  s    "z;InstructBlipForConditionalGeneration._preprocess_accelerateNF)rb   rb  rc  ra   r   c                 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 rt	|}tj
|
|gdd}| j|||	||dd	}|d ddd|	dddf }| |}|r|||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)rb   ra   r   r   NrU   r   r!   rX   )r.  rv   r/  r   r   r   )rC  r=   r>  rV   r   r   r   ri   rZ   ri  r`   rF  rH  )r3   rb   rb  rc  ra   r   r(   rk  rl  r   rm  rn  ro  rp  r4   r4   r5   get_image_features  s2      
$

z7InstructBlipForConditionalGeneration.get_image_featuresr[  c                 C   s`   |du r8||   tj| jjtj|jdk}|d}n|| jjk}|d	|
|j}|S r\  r]  r_  r4   r4   r5   ra    s    z9InstructBlipForConditionalGeneration.get_placeholder_mask)rb   rb  rc  r.  rv   rd  re  r   r   r   labelsr   ra   rf  r~   r,   c                 K   sd  |dur|n| j j}| j||||dd\}}}|s:| n|}|sJ| n|}|du rb|  |}|du rtt|}||j|j	}| j
||d}|||}| j jr| jf |||	|
||d|}|r|jn|d }d}|durR| jf ||| j jjd|}nL| jf |||||	|
|||d	|}|r6|jn|d }|rJ|jn|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)
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
            provided to serve as text prompt, which the language model can continue.

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

            [What are input IDs?](../glossary#input-ids)
        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.
        ```NTrb  rc  ra   r   rg  rh  r   )r'   rw  r)  )	r   rv   rd  re  r   r   r   rw  rf  r!   )r&   r'   r(   r)   r*   )rB   r   rv  r/   r   r=   ri  rf   r   rd   ra  rj  rP  rJ  r'   Zloss_functionrG  r)  r&   r%   )r3   rb   rb  rc  r.  rv   rd  re  r   r   r   rw  r   ra   rf  r~   rp  r(   rn  r`  r   r'   r&   r4   r4   r5   rl     st    X

	

z,InstructBlipForConditionalGeneration.forward)rb   rb  rc  r.  rv   r   ra   r,   c                 K   s  t | dr|   |jd }	| j||||dd\}
}}|du r|du r| jjg| jj }|| jjjg }t	j
|gt	j|jd}||	d}|  |}|du rt	|}|
|j|j}
| j||d}|||
}||d	}| jjjs||d
< | jjf 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.
        rV  r   Trx  Nr   r!   rg  )r   rv   r.  )r   rZ  rZ   rv  rB   Zimage_token_indexrD  rG  Zbos_token_idr=   r   r   r   repeatr   ri  rf   rd   ra  rj  rJ  Zis_encoder_decodergenerate)r3   rb   rb  rc  r.  rv   r   ra   Zgenerate_kwargsrj   rp  r(   rn  Zimage_tokensZstart_tokensr`  inputsr   r4   r4   r5   rz  g  s6    "




z-InstructBlipForConditionalGeneration.generate)NFF)NNNNNNNNNNFN)NNNNNF)%r9   r:   r;   r"   r?   r   r   rL  rD   r   r3  rr  r   Modulers  rt  ru  rR  rZ  r=   r>   r@  r   ro   rv  ra  r   r   r   r   r   r7   r%   rl   Zno_gradrz  rp   r4   r4   rP   r5   r   9  s   

   1            
       r   )r0  r   r   r   r   )rq   )Lr<   r   dataclassesr   typingr   r   r   r   r=   Ztorch.utils.checkpointr   Zactivationsr	   Z
generationr
   Zmodeling_flash_attention_utilsr   Zmodeling_layersr   Zmodeling_outputsr   r   r   r   Zmodeling_utilsr   r   Zprocessing_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   r   autor   r   r    Zconfiguration_instructblipr"   r#   r$   Z
get_loggerr9   r   r%   r|  r@   rm   floatr   r   r   r   r   r   r   r   r   r  r  r  r  r#  r   r0  r   r   __all__r4   r4   r4   r5   <module>   s~    
R U0'P>}0`F3 @ B	  n