U
    ,-e                    @   sH  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mZ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  ddl!m"Z"m#Z# ddl$m%Z%m&Z&m'Z' e(e)Z*dZ+dgZ,eG dd deZ-G dd dej.Z/G dd dej.Z0G dd dej.Z1G dd dej.Z2G dd deZ3dZ4dZ5d Z6G d!d" d"ej.Z7G d#d$ d$e3Z8G d%d& d&ej.Z9G d'd( d(ej.Z:G d)d* d*ej.Z;G d+d, d,ej.Z<G d-d. d.ej.Z=G d/d0 d0ej.Z>G d1d2 d2ej.Z?G d3d4 d4ej.Z@G d5d6 d6e3ZAed7e4G d8d9 d9e3ZBdS ):z PyTorch InstructBLIP model.    N)	dataclass)AnyOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsBaseModelOutputWithPooling,BaseModelOutputWithPoolingAndCrossAttentions)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )AutoModelForCausalLMAutoModelForSeq2SeqLM   )InstructBlipConfigInstructBlipQFormerConfigInstructBlipVisionConfigz"Salesforce/instructblip-flan-t5-xlc                   @   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)  
    Class defining the outputs of [`InstructBlipForConditionalGeneration`].

    Args:
        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 kr | nt  | V  qdS ))r"   r#   r$   N)getattrto_tuple).0kself w/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/instructblip/modeling_instructblip.py	<genexpr>R   s   
zKInstructBlipForConditionalGenerationModelOutput.to_tuple.<locals>.<genexpr>)tuplekeysr+   r-   r+   r.   r(   Q   s    z8InstructBlipForConditionalGenerationModelOutput.to_tuple)__name__
__module____qualname____doc__r    r   r   torchFloatTensor__annotations__r!   r"   r#   r$   r   r(   r-   r-   r-   r.   r   8   s   
r   c                       s6   e Zd Zed fddZej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__r;   hidden_size	embed_dimZ
image_sizeZ
patch_sizer   	Parameterr6   Zrandnclass_embeddingConv2dpatch_embeddingZnum_patchesZnum_positionsposition_embeddingr,   r;   	__class__r-   r.   r=   \   s    
   z%InstructBlipVisionEmbeddings.__init__)pixel_valuesr&   c                 C   s   |j d }| jjj}| |j|d}|ddd}| j|dd|}t	j
||gdd}|| jd d d |dd d f | }|S )Nr   dtyper   r   dim)shaperC   weightrJ   toflatten	transposerA   expandr6   catrD   size)r,   rH   
batch_sizeZtarget_dtypeZpatch_embedsZclass_embeds
embeddingsr-   r-   r.   forwardn   s    

,z$InstructBlipVisionEmbeddings.forward)
r2   r3   r4   r   r=   r6   r7   TensorrX   __classcell__r-   r-   rF   r.   r9   [   s   r9   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 | _	t
|j| _t
j| jd| j dd| _|jrt
t| j}t
t| j}nd }d }|d k	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      r	   F)bias)Zrequires_grad)r<   r=   r;   r>   r?   num_attention_heads	num_headshead_dim
ValueErrorscaler   DropoutZattention_dropoutdropoutLinearqkvqkv_biasr@   r6   zerosrT   Z
zeros_liker\   
projection)r,   r;   Zq_biasZv_biasrf   rF   r-   r.   r=   ~   s*    
zInstructBlipAttention.__init__)tensorseq_lenbszc                 C   s    | ||| j| jdd S )Nr   r   )viewr^   r_   rR   
contiguous)r,   ri   rj   rk   r-   r-   r.   _shape   s    zInstructBlipAttention._shapeNF)hidden_states	head_maskoutput_attentionsr&   c                 C   s   |  \}}}| |}|||d| j|| j ddddd}|d |d |d   }}	}
t||	dd}|| j }t	j
j|dd}| |}|d	k	r|| }t||
dddd}|  d	d | jf }||}| |}|r||fn|d	f}|S )
z#Input shape: Batch x Time x Channelr	   r   r   r      rK   rL   N)rU   re   Zreshaper^   permuter6   matmulrR   ra   r   Z
functionalZsoftmaxrc   r?   rh   )r,   ro   rp   rq   rk   Ztgt_lenr?   Z	mixed_qkvZquery_statesZ
key_statesZvalue_statesattention_scoresattention_probscontext_layernew_context_layer_shapeoutputoutputsr-   r-   r.   rX      s,    
    



zInstructBlipAttention.forward)NF)r2   r3   r4   r5   r=   r6   rY   intrn   r   boolr   rX   rZ   r-   r-   rF   r.   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)r<   r=   r;   r
   
hidden_actactivation_fnr   rd   r>   intermediate_sizefc1fc2rE   rF   r-   r.   r=      s
    
zInstructBlipMLP.__init__ro   r&   c                 C   s"   |  |}| |}| |}|S r   )r   r   r   r,   ro   r-   r-   r.   rX      s    


zInstructBlipMLP.forwardr2   r3   r4   r=   r6   rY   rX   rZ   r-   r-   rF   r.   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 )	InstructBlipEncoderLayerr:   c                    sR   t    |j| _t|| _tj| j|jd| _	t
|| _tj| j|jd| _d S NZeps)r<   r=   r>   r?   r[   	self_attnr   	LayerNormlayer_norm_epslayer_norm1r~   mlplayer_norm2rE   rF   r-   r.   r=      s    


z!InstructBlipEncoderLayer.__init__F)ro   attention_maskrq   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.
        )ro   rp   rq   )r   r   r   r   )r,   ro   r   rq   ZresidualZattn_weightsr{   r-   r-   r.   rX      s     




z InstructBlipEncoderLayer.forward)F)r2   r3   r4   r   r=   r6   rY   r   r}   r   r7   rX   rZ   r-   r-   rF   r.   r      s    r   c                   @   s>   e Zd ZdZeZdZdZddddgZg Z	dd	 Z
dddZdS )InstructBlipPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ZblipTInstructBlipQFormerEmbeddingsr[   %InstructBlipQFormerMultiHeadAttentionInstructBlipQFormerSelfOutputc                 C   s   | j j}t|tjs,t|tjs,t|tjr^|jjj	d|d t
|dr^|jdk	r^|jj  t|trt
| j dr~| j jj}tjj|jd|d tjj|jd|d nJt|tjr|jj  |jjd n"t|tjr|jdk	r|jj  dS )zInitialize the weightsg        )meanZstdr\   Nvision_config      ?)r;   Zinitializer_range
isinstancer   rB   	Embeddingrd   rO   dataZnormal_hasattrr\   Zzero_r9   r   initZtrunc_normal_rD   rA   r   Zfill_)r,   modulefactorr-   r-   r.   _init_weights  s    $

z)InstructBlipPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S r   )r   InstructBlipEncodergradient_checkpointing)r,   r   valuer-   r-   r.   _set_gradient_checkpointing3  s    
z7InstructBlipPreTrainedModel._set_gradient_checkpointingN)F)r2   r3   r4   r5   r   config_classZbase_model_prefixZsupports_gradient_checkpointing_no_split_modules_keep_in_fp32_modulesr   r   r-   r-   r-   r.   r     s   r   aE  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`InstructBlipConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`InstructBlipProcessor`]. See
            [`InstructBlipProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
a1  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`InstructBlipProcessor`]. See
            [`InstructBlipProcessor.__call__`] for details.

        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)

        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_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an
            encoder-decoder language model (like T5) is used.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-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.

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                       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 )
r   a  
    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`.
    r:   c                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r-   )r   )r)   _r:   r-   r.   
<listcomp>  s     z0InstructBlipEncoder.__init__.<locals>.<listcomp>F)	r<   r=   r;   r   
ModuleListrangenum_hidden_layerslayersr   rE   rF   r:   r.   r=     s    
 zInstructBlipEncoder.__init__N)r   rq   output_hidden_statesreturn_dictr&   c                    s
   dk	r n| j j |dk	r |n| j j}|dk	r4|n| j j}|rDdnd} rPdnd}|}t| jD ]n\}	}
|rx||f }| jr| jr fdd}tj	j

||
||}n|
|| 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.
        Nr-   c                    s    fdd}|S )Nc                     s    | f S r   r-   inputs)r   rq   r-   r.   custom_forward  s    zRInstructBlipEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr-   r   r   rq   r   r.   create_custom_forward  s    z:InstructBlipEncoder.forward.<locals>.create_custom_forwardr   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r-   r)   vr-   r-   r.   r/     s      z.InstructBlipEncoder.forward.<locals>.<genexpr>)last_hidden_statero   
attentions)r;   rq   r   use_return_dict	enumerater   r   trainingr6   utils
checkpointr0   r   )r,   inputs_embedsr   rq   r   r   Zencoder_statesZall_attentionsro   idxZencoder_layerr   layer_outputsr-   r   r.   rX     sD    

  zInstructBlipEncoder.forward)NNNN)r2   r3   r4   r5   r   r=   r   r6   rY   r}   r   r   r   rX   rZ   r-   r-   rF   r.   r     s   		    
r   c                
       sx   e Zd ZdZeZed fddZeee	e
eddeej ee ee ee eee
f ddd	Zd
d Z  ZS )InstructBlipVisionModelrH   r:   c                    sJ   t  | || _|j}t|| _t|| _tj	||j
d| _|   d S r   )r<   r=   r;   r>   r9   rW   r   encoderr   r   r   post_layernorm	post_init)r,   r;   r?   rF   r-   r.   r=     s    

z InstructBlipVisionModel.__init__output_typer   N)rH   rq   r   r   r&   c           	      C   s   |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}|dkrLtd| |}| j||||d}|d }| |}|dddddf }| |}|s||f|dd  S t|||j	|j
dS )z
        Returns:

        Nz You have to specify pixel_values)r   rq   r   r   r   r   )r   pooler_outputro   r   )r;   rq   r   r   r`   rW   r   r   r   ro   r   )	r,   rH   rq   r   r   ro   encoder_outputsr   pooled_outputr-   r-   r.   rX     s2    


zInstructBlipVisionModel.forwardc                 C   s   | j S r   )rW   r+   r-   r-   r.   get_input_embeddings2  s    z,InstructBlipVisionModel.get_input_embeddings)NNNN)r2   r3   r4   main_input_namer   r   r=   r   $INSTRUCTBLIP_VISION_INPUTS_DOCSTRINGr   r   r   r6   r7   r}   r   r   rX   r   rZ   r-   r-   rF   r.   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)r<   r=   r;   r>   r]   r   r`   r|   attention_head_sizeall_head_sizer   rd   queryZencoder_hidden_sizekeyr   rb   Zattention_probs_dropout_probrc   r'   r   max_position_embeddingsr   distance_embeddingsave_attentionr,   r;   is_cross_attentionrF   r-   r.   r=   7  s.    

z.InstructBlipQFormerMultiHeadAttention.__init__c                 C   s
   || _ d S r   attn_gradients)r,   r   r-   r-   r.   save_attn_gradientsS  s    z9InstructBlipQFormerMultiHeadAttention.save_attn_gradientsc                 C   s   | j S r   r   r+   r-   r-   r.   get_attn_gradientsV  s    z8InstructBlipQFormerMultiHeadAttention.get_attn_gradientsc                 C   s
   || _ d S r   attention_map)r,   r   r-   r-   r.   save_attention_mapY  s    z8InstructBlipQFormerMultiHeadAttention.save_attention_mapc                 C   s   | j S r   r   r+   r-   r-   r.   get_attention_map\  s    z7InstructBlipQFormerMultiHeadAttention.get_attention_mapc                 C   s6   |  d d | j| jf }|j| }|ddddS )NrK   r   r   r   r	   )rU   r]   r   rl   rt   )r,   xZnew_x_shaper-   r-   r.   transpose_for_scores_  s    
z:InstructBlipQFormerMultiHeadAttention.transpose_for_scoresNc                 C   s  |d k	}|r2|  | |}	|  | |}
|}nv|d k	r|  | |}	|  | |}
tj|d |	gdd}	tj|d |
gdd}
n |  | |}	|  | |}
| |}|  |}|	|
f}t||	dd}| jdks| 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||}|| }n4| jdkrtd||}td|	|}|| | }|t| j }|j}|d k	r|| }tjdd||}|r| jr| | || j | |}|d k	r2|| }t||
}|dddd }|	 d d | jf }|j| }|r||fn|f}||f }|S )Nr   r   rL   r   rK   rs   r   r   rJ   devicerI   zbhld,lrd->bhlrzbhrd,lrd->bhlrr	   ) r   r   r   r6   rT   r   ru   rR   r   rU   arangelongr   rl   r   r   rP   rJ   Zeinsummathsqrtr   r   ZSoftmaxr   r   register_hookr   rc   rt   rm   r   )r,   ro   r   rp   encoder_hidden_statesencoder_attention_maskpast_key_valuerq   r   Z	key_layerZvalue_layerZmixed_query_layerZquery_layerrv   
seq_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_scores_dtyperw   Zattention_probs_droppedrx   ry   r{   r-   r-   r.   rX   d  s`    








z-InstructBlipQFormerMultiHeadAttention.forward)F)NNNNNF)r2   r3   r4   r=   r   r   r   r   r   rX   rZ   r-   r-   rF   r.   r   6  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   )r<   r=   r   rd   r>   denser   r   rb   hidden_dropout_probrc   rE   rF   r-   r.   r=     s    
z&InstructBlipQFormerSelfOutput.__init__ro   input_tensorr&   c                 C   s&   |  |}| |}| || }|S r   r   rc   r   r,   ro   r   r-   r-   r.   rX     s    

z%InstructBlipQFormerSelfOutput.forwardr   r-   r-   rF   r.   r     s   r   c                
       sv   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   ee
 e	ej ddd	Z  ZS )InstructBlipQFormerAttentionFc                    s,   t    t||| _t|| _t | _d S r   )r<   r=   r   	attentionr   rz   setpruned_headsr   rF   r-   r.   r=     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   rL   )lenr   r   r]   r   r   r   r   r   r   rz   r   r   union)r,   headsindexr-   r-   r.   prune_heads  s       z(InstructBlipQFormerAttention.prune_headsN)ro   r   rp   r   r   r   rq   r&   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )r   rz   )r,   ro   r   rp   r   r   r   rq   Zself_outputsattention_outputr{   r-   r-   r.   rX     s    
	z$InstructBlipQFormerAttention.forward)F)NNNNNF)r2   r3   r4   r=   r   r6   rY   r   r7   r   r}   rX   rZ   r-   r-   rF   r.   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   )r<   r=   r   rd   r>   r   r   r   r   strr
   intermediate_act_fnrE   rF   r-   r.   r=     s
    
z(InstructBlipQFormerIntermediate.__init__r   c                 C   s   |  |}| |}|S r   )r   r  r   r-   r-   r.   rX     s    

z'InstructBlipQFormerIntermediate.forwardr   r-   r-   rF   r.   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   )r<   r=   r   rd   r   r>   r   r   r   rb   r   rc   rE   rF   r-   r.   r=     s    
z"InstructBlipQFormerOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   r-   r-   r.   rX     s    

z!InstructBlipQFormerOutput.forwardr   r-   r-   rF   r.   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)r<   r=   chunk_size_feed_forwardseq_len_dimr   r   	layer_idxZcross_attention_frequencycrossattentionhas_cross_attentionr  intermediater  rz   intermediate_queryoutput_query)r,   r;   r  rF   r-   r.   r=     s    




z!InstructBlipQFormerLayer.__init__NFr   c	              	   C   s>  |d k	r|d d nd }	| j |||||	d}
|
d }|
dd }|
d }|dkr|d d d |d d f }| jr|d krtd| j||||||d}|d }||dd  }t| j| j| j|}|jd |kr&t| j	| j| j|d d |d d d f }t
j||gdd}nt| j	| j| j|}|f| }||f }|S )	Nr   )rq   r   r   r   rK   z>encoder_hidden_states must be given for cross-attention layersr   rL   )r   r
  r`   r	  r   feed_forward_chunk_queryr  r  rN   feed_forward_chunkr6   rT   )r,   ro   r   rp   r   r   r   rq   query_lengthZself_attn_past_key_valueZself_attention_outputsr   r{   Zpresent_key_valueZquery_attention_outputZcross_attention_outputslayer_outputZlayer_output_textr-   r-   r.   rX   0  sb    


z InstructBlipQFormerLayer.forwardc                 C   s   |  |}| ||}|S r   )r  rz   r,   r   Zintermediate_outputr  r-   r-   r.   r  w  s    
z+InstructBlipQFormerLayer.feed_forward_chunkc                 C   s   |  |}| ||}|S r   )r  r  r  r-   r-   r.   r  |  s    
z1InstructBlipQFormerLayer.feed_forward_chunk_query)NNNNNFr   )r2   r3   r4   r=   rX   r  r  rZ   r-   r-   rF   r.   r    s          
G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 r-   )r  )r)   r  r:   r-   r.   r     s     z7InstructBlipQFormerEncoder.__init__.<locals>.<listcomp>F)	r<   r=   r;   r   r   r   r   layerr   rE   rF   r:   r.   r=     s    
z#InstructBlipQFormerEncoder.__init__NFTr   c              
      sr  |	rdnd } rdnd } r dnd }|r,dnd }t | jjD ]}| j| }|	rX||f }|d k	rh|| nd }|d k	r||| nd t| jddr| jr|rtd d} fdd}tj	j

|||||||}n|||||| }|d }|r||d f7 } r<||d	 f }|jr<||d
 f }q<|	r>||f }|
s`tdd |||||fD S t|||||dS )Nr-   r   FzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...c                    s    fdd}|S )Nc                     s    | f S r   r-   r   )r   rq   r   r  r-   r.   r     s    zYInstructBlipQFormerEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr-   r   rq   r   r  r   r.   r     s    zAInstructBlipQFormerEncoder.forward.<locals>.create_custom_forwardr   rK   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r-   r   r-   r-   r.   r/     s   z5InstructBlipQFormerEncoder.forward.<locals>.<genexpr>)r   past_key_valuesro   r   cross_attentions)r   r;   r   r  r'   r   loggerwarningr6   r   r   r
  r0   r   )r,   ro   r   rp   r   r   r  	use_cacherq   r   r   r  Zall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskr   r   r-   r  r.   rX     sx    

	
z"InstructBlipQFormerEncoder.forward)
NNNNNNFFTr   )r2   r3   r4   r=   rX   rZ   r-   r-   rF   r.   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   rK   F)
persistentr   r   )r<   r=   r   r   
vocab_sizer>   Zpad_token_idword_embeddingsr   position_embeddingsr   r   	layernormrb   r   rc   Zregister_bufferr6   r   rS   r'   r   r;   rE   rF   r-   r.   r=     s    
  z&InstructBlipQFormerEmbeddings.__init__Nr   c                 C   s   |d k	r|  d }nd}|d kr@| jd d ||| f  }|d k	r| |}| jdkrv| ||j}|| }|d k	rtj	||fdd}n|}|| j
jj}| 
|}| |}|S )Nr   r   r   rL   )rU   r  cloner  r   r   rP   r   r6   rT   r!  rO   rJ   rc   )r,   	input_idsr  query_embedspast_key_values_lengthr   rW   r   r-   r-   r.   rX     s"    



z%InstructBlipQFormerEmbeddings.forward)NNNr   )r2   r3   r4   r5   r=   rX   rZ   r-   r-   rF   r.   r     s       r   c                       s   e 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	j   ee 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.
    r:   c                    s2   t  | || _t|| _t|| _|   d S r   )r<   r=   r;   r   rW   r  r   r   rE   rF   r-   r.   r=   "  s
    

z!InstructBlipQFormerModel.__init__c                 C   s   | j jS r   rW   r  r+   r-   r-   r.   r   ,  s    z-InstructBlipQFormerModel.get_input_embeddingsc                 C   s   || j _d S r   r'  r,   r   r-   r-   r.   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   )r,   Zheads_to_pruner  r   r-   r-   r.   _prune_heads2  s    z%InstructBlipQFormerModel._prune_headsF)r   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 )rI   r   g     )rM   r`   rN   rP   rJ   )r,   r   r,  r   r-  extended_attention_maskr-   r-   r.   get_extended_attention_mask:  s    	z4InstructBlipQFormerModel.get_extended_attention_maskN)r#  r   r  r$  rp   r   r   r  r  rq   r   r   r&   c                    s  |
dk	r|
n j j}
|dk	r |n j j}|dk	r4|n j j}|dkrT|dkrTtd|dk	rv|d d jd  j j nd}|dk	r|jd nd} j||||d}| dd }|\}}|j	}|dkrt
j||| f|d} |||}|dk	rt|tkr|d  \}}}n| \}}}||f}t|tkrP fd	d
|D }n.|dkrtt
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 (`tuple(tuple(torch.FloatTensor))` 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  r$  r%  rK   )r   c                    s   g | ]}  |qS r-   )invert_attention_mask)r)   maskr+   r-   r.   r     s     z4InstructBlipQFormerModel.forward.<locals>.<listcomp>)
r   rp   r   r   r  r  rq   r   r   r  )r   r   r  ro   r   r  )r;   rq   r   r   r`   rN   r  rW   rU   r   r6   onesr0  typelistr1  Zget_head_maskr   r   r   r  ro   r   r  )r,   r#  r   r  r$  rp   r   r   r  r  rq   r   r   r%  r  Zembedding_outputr,  rV   r   r   r/  Zencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskr   Zsequence_outputr   r-   r+   r.   rX   e  sv    "$

z InstructBlipQFormerModel.forward)F)NNNNNNNNNNN)r2   r3   r4   r5   r   r=   r   r)  r+  r6   rY   r   r|   r   r}   r0  
LongTensorr   r7   r   r   rX   rZ   r-   r-   rF   r.   r&    sN   
 .           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eZd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eeeeeddej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f dddZe dejeej eej eej eej ejdddZ  Z S ) $InstructBlipForConditionalGenerationrH   r:   c                    s   t  | t|j| _ttd|j	|j
j| _t|j
| _t|j
j|jj| _|jrjt|j}nt|j}|jd k	r| j|j |jd k	r| j|j || _|   d S )Nr   )r<   r=   r   r   vision_modelr   r@   r6   rg   Znum_query_tokensZqformer_configr>   query_tokensr&  qformerrd   text_configlanguage_projectionuse_decoder_only_language_modelr   from_configr   r   extendr   language_modelr   )r,   r;   r@  rF   r-   r.   r=     s    

z-InstructBlipForConditionalGeneration.__init__c                 C   s
   | j  S r   )r@  r   r+   r-   r-   r.   r     s    z9InstructBlipForConditionalGeneration.get_input_embeddingsc                 C   s   | j | d S r   )r@  r)  r(  r-   r-   r.   r)    s    z9InstructBlipForConditionalGeneration.set_input_embeddingsc                 C   s   | j | d S r   )r@  set_output_embeddings)r,   Znew_embeddingsr-   r-   r.   rA    s    z:InstructBlipForConditionalGeneration.set_output_embeddingsr%   c                 C   s
   | j  S r   )r@  get_output_embeddingsr+   r-   r-   r.   rB    s    z:InstructBlipForConditionalGeneration.get_output_embeddingsc                 C   s
   | j  S r   )r@  get_encoderr+   r-   r-   r.   rC    s    z0InstructBlipForConditionalGeneration.get_encoderc                 C   s
   | j  S r   )r@  get_decoderr+   r-   r-   r.   rD    s    z0InstructBlipForConditionalGeneration.get_decoderc                 C   s(   | j js$| jj| jj_| jj| jj_d S r   )r;   r=  r@  Zsharedr   Zembed_tokensdecoderr+   r-   r-   r.   _tie_weights  s    z1InstructBlipForConditionalGeneration._tie_weightsc                 C   sL   | j }t|dkr2d|k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   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_mapr   r6   cudaZdevice_countr  r  r   r@  rG  Zio_same_device)r,   rH  r-   r-   r.   _preprocess_accelerate  s    "z;InstructBlipForConditionalGeneration._preprocess_accelerater   N)rH   qformer_input_idsqformer_attention_maskr#  r   decoder_input_idsdecoder_attention_maskrq   r   labelsr   r&   c              
   C   s  |dk	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krt|}tj||gdd}| j|||||||	|d}|d ddd|dddf }| |}tj| dd tj|jd}| j |}tj|||jgdd}|dkrLt|}tj||j|gdd}| j jr4| j||||	|d	}|r|jn|d }d}|
dk	rv|
|j}
|dd|
d dddf }|d
ddddf  }|
d
ddf  |j}tdd}||d| j jj|d}nB| j||||||	||
d}|rZ|jn|d }|rn|jn|d }|s||||f}|dk	r|f| S |S t|||||dS )a  
        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]`

        Returns:

        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.
        ```N)rH   rq   r   r   r   rK   r   r   rL   )r#  r   r$  r   r   rq   r   r   )r   r   rq   r   r   .r   )Z	reduction)r   r   rM  rN  rq   r   r   rO  )r    r!   r"   r#   r$   )r;   r   r8  r6   r3  rU   r   r   r9  rS   rN   	ones_likerT   r:  r<  r@  r   rP   r=  r!   rm   r   rl   r;  r  r    r   )r,   rH   rK  rL  r#  r   rM  rN  rq   r   rO  r   r"   image_embedsimage_attention_maskr9  query_attention_maskquery_outputsquery_outputlanguage_model_inputsZlanguage_model_attention_maskr   r{   r!   r    Zshift_logitsZshift_labelsZloss_fctrz   r-   r-   r.   rX   3  s    <  

$
  



"
 
z,InstructBlipForConditionalGeneration.forward)rH   rK  rL  r#  r   r&   c                 K   s  t | dr|   |jd }| j|ddj}tj| dd tj|j	d}	| j
|jd dd}
tj|
 dd tj|j	d}|dkrt|}tj||gdd	}| j|||
||	dd
}|jddd|
dddf }| |}tj| dd tj|j	d}|dkr6t| jjjgg|d|j	}|dkrJt|}tj|||j	gdd	}|  |}tj|||j	gdd	}| jjf ||d|}| jjjd dkrt|tjrd||dk< nd|j|jdk< |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.

        Returns:
            captions (list): A list of strings of length batch_size * num_captions.
        rH  r   T)r   NrK   r   r   rL   )r#  r   r$  r   r   r   )r   r   ZLLaMAForCausalLMr   )r   rJ  rN   r8  r   r6   r3  rU   r   r   r9  rS   rP  rT   r:  r<  r6  r;   r;  Zbos_token_idrepeatrP   r   r@  generateZarchitecturesr   rY   	sequences)r,   rH   rK  rL  r#  r   Zgenerate_kwargsrV   rQ  rR  r9  rS  rT  rU  rV  Zlanguage_attention_maskr   r{   r-   r-   r.   rX    sb    

  
"
  
 

	z-InstructBlipForConditionalGeneration.generate)	NNNNNNNNN)NNNN)!r2   r3   r4   r   r   r   r=   r   r)  rA  r   ModulerB  rC  rD  rF  rJ  r   INSTRUCTBLIP_INPUTS_DOCSTRINGr   r   r   r6   r7   r   r6  r}   r   r   rX   Zno_gradrX  rZ   r-   r-   rF   r.   r7    sj             
     r7  )Cr5   r   dataclassesr   typingr   r   r   r   r6   Ztorch.utils.checkpointr   Ztorch.nnr   Zactivationsr
   Zmodeling_outputsr   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r   r   r   r   r   r   autor   r   Zconfiguration_instructblipr   r   r   Z
get_loggerr2   r  Z_CHECKPOINT_FOR_DOCZ*INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LISTr   rZ  r9   r[   r~   r   r   ZINSTRUCTBLIP_START_DOCSTRINGr   r[  r   r   r   r   r   r  r  r  r  r   r&  r7  r-   r-   r-   r.   <module>   s\   
! R0+A]B 2hf3 E
