o
    hj                     @   s$  d 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 eeZdZ g dZ!eG dd deZ"G dd de
j#Z$dZ%ede%G dd deZ&dZ'ede%G dd de&Z(dS )z PyTorch Llava model.    )	dataclass)ListOptionalTupleUnionN)nn   )PreTrainedModel)ACT2FN)Cache)ModelOutput)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )	AutoModelAutoModelForCausalLM   )LlavaConfigr   )zllava-hf/llava-1.5-7b-hfzllava-hf/llava-1.5-13b-hfzllava-hf/bakLlava-v1-hfc                   @   s   e Zd ZU dZdZeej ed< dZ	ejed< dZ
eeej  ed< dZeeej  ed< dZeeej  ed< dZeeej  ed< dS )	LlavaCausalLMOutputWithPasta  
    Base class for Llava causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
            sequence_length, hidden_size)`.

            image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
    Nlosslogitspast_key_valueshidden_states
attentionsimage_hidden_states)__name__
__module____qualname____doc__r   r   torchFloatTensor__annotations__r   r   r   r   r   r   r    r$   r$   ^/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/llava/modeling_llava.pyr   1   s   
  r   c                       s*   e Zd Zdef fddZdd Z  ZS )LlavaMultiModalProjectorconfigc                    sN   t    tj|jj|jjdd| _t|j	 | _
tj|jj|jjdd| _d S )NT)bias)super__init__r   Linearvision_confighidden_sizetext_configlinear_1r
   projector_hidden_actactlinear_2selfr'   	__class__r$   r%   r*   ]   s   
z!LlavaMultiModalProjector.__init__c                 C   s"   |  |}| |}| |}|S N)r/   r1   r2   )r4   image_featuresr   r$   r$   r%   forwardd   s   


z LlavaMultiModalProjector.forward)r   r   r   r   r*   r9   __classcell__r$   r$   r5   r%   r&   \   s    r&   ac  
    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 ([`LlavaConfig`] or [`LlavaVisionConfig`]):
            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.
zSThe bare LLaMA Model outputting raw hidden-states without any specific head on top.c                   @   s*   e Zd ZeZdZdZdgZdZdd Z	dS )LlavaPreTrainedModelmodelTLlavaVisionAttentionc                 C   s   t | jdr
| jjn| jjj}t |dr|jjjd|d t|tj	tj
fr>|jjjd|d |jd ur<|jj  d S d S t|tjr]|jjjd|d |jd ur_|jj|j   d S d S d S )Ninitializer_rangeclass_embeddingg        )meanstd)hasattrr'   r>   r.   r?   datanormal_
isinstancer   r+   Conv2dweightr(   zero_	Embeddingpadding_idx)r4   modulerA   r$   r$   r%   _init_weights   s"   




z"LlavaPreTrainedModel._init_weightsN)
r   r   r   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2rL   r$   r$   r$   r%   r;   |   s    r;   a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
            The tensors corresponding to the input images. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
            [`CLIPImageProcessor`] for processing images).
        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)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential 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)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        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`).
        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.
zIThe LLAVA model which consists of a vision backbone and a language model.c                !       sH  e Zd Zdef fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zd-dee dejfddZdd Zeeeeed													d.dejdejdeej deej deeej  deej d ee d!ee d"eej d#ee d$ee d%ee d&ee deeef fd'd(Z 	d/d)d*Z!d+d, Z"  Z#S )0LlavaForConditionalGenerationr'   c                    sf   t  | t|j| _t|| _|j| _t	j|j
|jd| _| jjd ur*| jjnd| _|   d S )N)attn_implementation)r)   r*   r   from_configr,   vision_towerr&   multi_modal_projector
vocab_sizer   r.   _attn_implementationlanguage_modelr'   pad_token_id	post_initr3   r5   r$   r%   r*      s   
z&LlavaForConditionalGeneration.__init__c                 C   
   | j  S r7   )rZ   get_input_embeddingsr4   r$   r$   r%   r^         
z2LlavaForConditionalGeneration.get_input_embeddingsc                 C      | j | d S r7   )rZ   set_input_embeddings)r4   valuer$   r$   r%   rb         z2LlavaForConditionalGeneration.set_input_embeddingsc                 C   r]   r7   )rZ   get_output_embeddingsr_   r$   r$   r%   re      r`   z3LlavaForConditionalGeneration.get_output_embeddingsc                 C   ra   r7   )rZ   set_output_embeddings)r4   new_embeddingsr$   r$   r%   rf      rd   z3LlavaForConditionalGeneration.set_output_embeddingsc                 C   ra   r7   )rZ   set_decoder)r4   decoderr$   r$   r%   rh      rd   z)LlavaForConditionalGeneration.set_decoderc                 C   r]   r7   )rZ   get_decoderr_   r$   r$   r%   rj      r`   z)LlavaForConditionalGeneration.get_decoderc                 C   r]   r7   )rZ   tie_weightsr_   r$   r$   r%   rk     r`   z)LlavaForConditionalGeneration.tie_weightsNnew_num_tokensreturnc                 C   s0   | j ||}|j| jj_|j| j_|j| _|S r7   )rZ   resize_token_embeddingsnum_embeddingsr'   r.   rX   )r4   rl   pad_to_multiple_ofmodel_embedsr$   r$   r%   rn     s
   
z5LlavaForConditionalGeneration.resize_token_embeddingsc                 C   s  |j \}}}|j \}	}
t|d d df t| jk }|| jjk}tj|dd}| |d  |
 }t|| jjk\}}t	||d  d dd }|d |d d df  }|re||d d d f 7 }|||f }tj
|	|||j|jd}tj
|	||j|jd}|||f |||f< |||f |||f< tj|dkdd}||	dd |d d d f kM }| |j d d  krtdt| d| d| d|||< ||O }|	dd |dkd}|||fS )	NrT   dimr   dtypedevicer   zIThe input provided to the model are wrong. The number of image tokens is z1 while the number of image given to the model is z=. This prevents correct indexing and breaks batch generation.)shaper!   sumtensorr[   r'   image_token_indexmaxwherecumsumzerosru   rv   allnumel
ValueError
contiguousreshapemasked_fill_)r4   r8   inputs_embeds	input_idsattention_maskposition_ids
num_imagesnum_image_patches	embed_dim
batch_sizesequence_lengthleft_paddingspecial_image_token_masknum_special_image_tokensmax_embed_dimbatch_indicesnon_image_indicesnew_token_positionsnb_image_padtext_to_overwritefinal_embeddingfinal_attention_maskimage_to_overwriter$   r$   r%   $_merge_input_ids_with_image_features  s@   
$"
zBLlavaForConditionalGeneration._merge_input_ids_with_image_features)output_typerM   r   pixel_valuesr   r   r   r   vision_feature_layervision_feature_select_strategylabels	use_cacheoutput_attentionsoutput_hidden_statesreturn_dictc              
   C   s"  |dur|n| j j}|dur|n| j j}|dur|n| j j}|dur$|n| j j}|dur.|n| j j}|du r|  |}|dur|jd dkr| j|dd}|j	| }|dkrb|ddddf }n|dkri|}n	t
d| j j | |}| |||||\}}}|	du rt|| j jtj}	n^|dur|dur|jd dkr|d d ddddddf }t|dk\}}|jd	 d }tj|jd ||jd  f|j|jd
}d|||f< tj||fdd}tj|ddd	d }| j|||||
|||d}|d }d}|	durm|dur?|dddf }|ddd	ddf ||jdk  }|	dddf ||	jdk  }n|ddd	ddf  }|	dddf  }t }||d	|d	|d	|j}|s|f|dd  }|dur|f| S |S t|||j |j	|j!dS )ag  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:

        Example:

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

        >>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
        >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")

        >>> prompt = "<image>\nUSER: What's the content of the image?\nASSISTANT:"
        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(text=text, images=image, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(**inputs, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "There seems to be a stop sign"
        ```Nr   T)r   defaultfullz$Unexpected select feature strategy: r   rT   rt   rr   )r   r   r   r   r   r   r   r   .)r   r   r   r   r   )"r'   r   r   use_return_dictr   r   r^   rw   rV   r   r   rW   r   r!   	full_likeignore_indextolongr|   onesru   rv   catrx   	unsqueezerZ   r   r   CrossEntropyLossviewsizer   r   r   )r4   r   r   r   r   r   r   r   r   r   r   r   r   r   image_outputsselected_image_featurer8   first_layer_past_key_valuebatch_indexnon_attended_tokenstarget_seqlenextended_attention_maskoutputsr   r   shift_attention_maskshift_logitsshift_labelsloss_fctoutputr$   r$   r%   r9   B  s   1



 

*& z%LlavaForConditionalGeneration.forwardc                 K   s  |d urzt |tr| }|j}n|d d jd  }}|d ur;|jd |jd kr;|d d |jd |  d f }n'||jd k rM|d d |d f }n| jj|v rb|d d |jd d d f }||k rz|d urz|d d ||jd   d f }|dd }	|d ur|	d u r| 	dd }	|	
|dkd |r|	d d |jd  d f }	|d ur|d u rd|i}
nd|i}
|
|	||d||d	 |
S )
Nr   r   r   r   rT   r   r   r   )r   r   r   r   r   )rE   r   get_seq_lengthseen_tokensrw   r'   rz   getr   r}   r   update)r4   r   r   r   r   r   kwargscache_lengthpast_lengthr   model_inputsr$   r$   r%   prepare_inputs_for_generation  s>   
" 
	z;LlavaForConditionalGeneration.prepare_inputs_for_generationc                 O   s   | j j|i |S r7   )rZ   _reorder_cache)r4   argsr   r$   r$   r%   r     s   z,LlavaForConditionalGeneration._reorder_cache)NN)NNNNNNNNNNNNN)NNNN)$r   r   r   r   r*   r^   rb   re   rf   rh   rj   rk   r   intr   rI   rn   r   r   LLAVA_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr!   
LongTensorr"   Tensorr   strboolr   r   r9   r   r   r:   r$   r$   r5   r%   rR      sv    4
	

 
5rR   ))r    dataclassesr   typingr   r   r   r   r!   torch.utils.checkpointr    r	   activationsr
   cache_utilsr   modeling_outputsr   utilsr   r   r   r   autor   r   configuration_llavar   
get_loggerr   loggerr   #LLAVA_PRETRAINED_MODEL_ARCHIVE_LISTr   Moduler&   LLAVA_START_DOCSTRINGr;   r   rR   r$   r$   r$   r%   <module>   s>   
)B