o
    Zhcg                     @   sp  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mZ ddlmZ ddlmZ ddlmZmZmZmZmZ ddlmZ ddl m!Z! e"e#Z$eG dd deZ%eG dd deZ&G dd de
j'Z(eG dd deZ)eddG dd de)Z*G dd deeZ+ed dG d!d" d"e)eZ,g d#Z-dS )$zPyTorch Llava model.    )	dataclass)ListOptionalTupleUnionN)nn   )ACT2FN)GenerationMixin)FlashAttentionKwargs)BaseModelOutputWithPastModelOutput)PreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torchdynamo_compilinglogging   )	AutoModel   )LlavaConfigc                   @   s$   e Zd ZU dZdZeej ed< dS )LlavaModelOutputWithPasta  
    Base class for Llava outputs, with hidden states and attentions.

    Args:
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        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 (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    Nimage_hidden_states)	__name__
__module____qualname____doc__r   r   torchFloatTensor__annotations__ r"   r"   W/var/www/auris/lib/python3.10/site-packages/transformers/models/llava/modeling_llava.pyr   &   s   
 r   c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eeej  ed< dZeeej  ed< dZeeej  ed< dZ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 (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    Nlosslogitspast_key_valueshidden_states
attentionsr   )r   r   r   r   r%   r   r   r    r!   r&   r'   r   r(   r   r)   r   r"   r"   r"   r#   r$   G   s   
 r$   c                       s*   e Zd Zdef fddZdd Z  ZS )LlavaMultiModalProjectorconfigc                    sp   t    t|jtrdnt|j}tj|jj	| |j
j	|jd| _t|j | _tj|j
j	|j
j	|jd| _d S )Nr   bias)super__init__
isinstancevision_feature_layerintlenr   Linearvision_confighidden_sizetext_configZmultimodal_projector_biaslinear_1r	   Zprojector_hidden_actactlinear_2)selfr+   Znum_feature_layers	__class__r"   r#   r/   p   s   

z!LlavaMultiModalProjector.__init__c                 C   s"   |  |}| |}| |}|S N)r8   r9   r:   )r;   image_featuresr(   r"   r"   r#   forward~   s   


z LlavaMultiModalProjector.forward)r   r   r   r   r/   r@   __classcell__r"   r"   r<   r#   r*   o   s    r*   c                   @   s<   e Zd ZeZdZdZdZdZdZ	dZ
dZdZdZdd ZdS )LlavaPreTrainedModel Tr'   c                 C   s   t | jd| j j}t|tjr)|jjj	d|d |j
d ur'|j
j  d S d S t|tjr>|jjd |j
j  d S d S )Ninitializer_rangeg        )meanstdg      ?)getattrr+   Zget_text_configrD   r0   r   r4   weightdataZnormal_r-   Zzero_Z	LayerNormZfill_)r;   modulerF   r"   r"   r#   _init_weights   s   
z"LlavaPreTrainedModel._init_weightsN)r   r   r   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_skip_keys_device_placementZ_supports_cache_classZ_supports_flash_attn_2Z_supports_sdpaZ_supports_quantized_cacheZ_supports_static_cacheZ_supports_attention_backendrK   r"   r"   r"   r#   rB      s    rB   zu
    The Llava model which consists of a vision backbone and a language model, without a language modeling head.
    )Zcustom_introc                %       s4  e Zd ZddiZdef fddZdd Zdd	 Z	
	
ddej	de
eeee f  de
e fddZee	
	
	
	
	
	
	
	
	
	
	
	
	
	
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eee f  de
e de
e de
e de
e de
e de
ej dejdee deeef f ddZ  ZS )!
LlavaModelzlanguage_model.modellanguage_modelr+   c                    s>   t  | t|j| _t|| _t|j| _	| 
  d S r>   )r.   r/   r   Zfrom_configr5   vision_towerr*   multi_modal_projectorr7   rM   	post_initr;   r+   r<   r"   r#   r/      s
   
zLlavaModel.__init__c                 C   
   | j  S r>   )rM   get_input_embeddingsr;   r"   r"   r#   rS         
zLlavaModel.get_input_embeddingsc                 C      | j | d S r>   )rM   set_input_embeddingsr;   valuer"   r"   r#   rW         zLlavaModel.set_input_embeddingsNpixel_valuesr1   vision_feature_select_strategyc                    s   |dur|n| j j}|dur|n| j j}|dvr!td| j j dd | D }| j|fddi| t|trN j| }|dkrM|ddd	df }n fd
d|D }|dkrbdd |D }t	j
|dd}| |}|S )a  
        Obtains image last hidden states from the vision tower and apply multimodal projection.

        Args:
            pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
               The tensors corresponding to the input images.
            vision_feature_layer (`Union[int, List[int]]`, *optional*):
                The index of the layer to select the vision feature. If multiple indices are provided,
                the vision feature of the corresponding indices will be concatenated to form the
                vision features.
            vision_feature_select_strategy (`str`, *optional*):
                The feature selection strategy used to select the vision feature from the vision backbone.
                Can be one of `"default"` or `"full"`
        Returns:
            image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
        N)defaultfullz$Unexpected select feature strategy: c                 S   s   i | ]\}}|d ur||qS r>   r"   ).0kvr"   r"   r#   
<dictcomp>   s    z1LlavaModel.get_image_features.<locals>.<dictcomp>output_hidden_statesTr]   r   c                    s   g | ]} j | qS r"   )r(   )r_   Z	layer_idxZimage_outputsr"   r#   
<listcomp>   s    z1LlavaModel.get_image_features.<locals>.<listcomp>c                 S   s    g | ]}|d d dd f qS )Nr   r"   )r_   hsr"   r"   r#   re      s     dim)r+   r1   r\   
ValueErroritemsrN   r0   r2   r(   r   catrO   )r;   r[   r1   r\   kwargsZselected_image_featureZhs_poolr?   r"   rd   r#   get_image_features   s*   


zLlavaModel.get_image_features	input_idsattention_maskposition_idsr'   inputs_embeds	use_cacheoutput_attentionsrc   return_dictcache_positionimage_sizesrm   returnc                 K   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 |d uA r>td|d u rH|  |}|d ur| j||||d}|d u rx||  t	j
| j jt	j|jdk}|jddjddd }n|| j jkd}|||j}|| j jk }t s||  | kr|| j jk }|jd |jd  }td| d	| ||j|j}|||}| jd|||||	|
|d
|d	|}t|j|j|j|j|d ur|dS d dS )Nz:You must specify exactly one of input_ids or inputs_embeds)r[   r1   r\   rw   )dtypedevicer   rh   r   rg   z6Image features and image tokens do not match: tokens: z, features T)	rp   rq   r'   rr   rs   rt   rc   ru   rv   )last_hidden_stater'   r(   r)   r   r"   )r+   rt   rc   use_return_dictr1   r\   rj   rS   rn   r   ZtensorZimage_token_idlongrz   sumZ	unsqueezeZ	expand_astor   Znumelshapery   Zmasked_scatterrM   r   r{   r'   r(   r)   )r;   ro   r[   rp   rq   r'   rr   r1   r\   rs   rt   rc   ru   rv   rw   rm   r?   Zspecial_image_maskZn_image_tokensZn_image_featuresoutputsr"   r"   r#   r@      sv   

zLlavaModel.forward)NN)NNNNNNNNNNNNNN)r   r   r   _checkpoint_conversion_mappingr   r/   rS   rW   r   r    r   r   r2   r   strrn   r   r   
LongTensorTensorboolr   r   r   r   r@   rA   r"   r"   r<   r#   rL      s~    
7	

rL   c                   @   s   e Zd ZdS )KwargsForCausalLMN)r   r   r   r"   r"   r"   r#   r   G  s    r   zS
    The LLAVA model which consists of a vision backbone and a language model.
    c                )       s  e Zd ZdddddZdgZdef fdd	Zd
d Zdd Zde	j
fddZdd Zedd Zedd Zedd Zee																d6d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eee f  d"ee d#eej d$ee d%ee d&ee d'ee d(eej d)eeejf d*eej d+ee deee f f$d,d-Z!						d7 fd.d/	Z"e#dejd0ed1ed2ej$d(ejd3efd4d5Z%  Z&S )8LlavaForConditionalGenerationzmodel.language_modelzmodel.vision_towerzmodel.multi_modal_projectorlm_head)z^language_model.modelz^vision_towerz^multi_modal_projectorz^language_model.lm_headzlm_head.weightr+   c                    s<   t  | t|| _tj|jj|jjdd| _	| 
  d S )NFr,   )r.   r/   rL   modelr   r4   r7   r6   
vocab_sizer   rP   rQ   r<   r"   r#   r/   X  s   
z&LlavaForConditionalGeneration.__init__c                 C   rR   r>   )r   rS   rT   r"   r"   r#   rS   ^  rU   z2LlavaForConditionalGeneration.get_input_embeddingsc                 C   rV   r>   )r   rW   rX   r"   r"   r#   rW   a  rZ   z2LlavaForConditionalGeneration.set_input_embeddingsrx   c                 C   s   | j S r>   r   rT   r"   r"   r#   get_output_embeddingsd  s   z3LlavaForConditionalGeneration.get_output_embeddingsc                 C   s
   || _ d S r>   r   )r;   Znew_embeddingsr"   r"   r#   set_output_embeddingsg  rU   z3LlavaForConditionalGeneration.set_output_embeddingsc                 C      | j jS r>   )r   rM   rT   r"   r"   r#   rM   k     z,LlavaForConditionalGeneration.language_modelc                 C   r   r>   )r   rN   rT   r"   r"   r#   rN   o  r   z*LlavaForConditionalGeneration.vision_towerc                 C   r   r>   )r   rO   rT   r"   r"   r#   rO   s  r   z3LlavaForConditionalGeneration.multi_modal_projectorNr   ro   r[   rp   rq   r'   rr   r1   r\   labelsrs   rt   rc   ru   rv   logits_to_keeprw   rm   c                 K   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}| jd|||||||||
||d||d|}|d }t|trXt	| dn|}| 
|dd|ddf }d}|	dur}| jd||	| j jjd|}t|||j|j|j|jdS )a  
        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]`.

        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 = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

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

        >>> # Generate
        >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "USER:  \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
        ```NT)ro   r[   rp   rq   r'   rr   r1   r\   rs   rt   rc   ru   rv   rw   r   )r&   r   r   )r%   r&   r'   r(   r)   r   r"   )r+   rt   rc   r|   r1   r\   r   r0   r2   slicer   Zloss_functionr7   r   r$   r'   r(   r)   r   )r;   ro   r[   rp   rq   r'   rr   r1   r\   r   rs   rt   rc   ru   rv   r   rw   rm   r   r(   Zslice_indicesr&   r%   r"   r"   r#   r@   w  s\   1z%LlavaForConditionalGeneration.forwardc           
         s8   t  j|f|||||d|}	|d dkr||	d< |	S )N)r'   rr   rp   rv   r   r   r[   )r.   prepare_inputs_for_generation)
r;   ro   r'   rr   r[   rp   rv   r   rm   Zmodel_inputsr<   r"   r#   r     s   
z;LlavaForConditionalGeneration.prepare_inputs_for_generationsequence_lengthtarget_lengthry   
batch_sizec                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )Z
fill_valuery   rz   r   )Zdiagonal)rz   rg   r   )ri   r   Zfinfominr^   rz   ZtriuZarangeZreshapeexpandcloner   r   Zmasked_fill)rp   r   r   ry   rv   r   rm   Zcausal_maskZ	min_dtypeZmask_lengthZpadding_maskr"   r"   r#   5_prepare_4d_causal_attention_mask_with_cache_position  s,    $
6  zSLlavaForConditionalGeneration._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNNNNNr   N)NNNNNN)'r   r   r   r   Z_tied_weights_keysr   r/   rS   rW   r   Moduler   r   propertyrM   rN   rO   r   r   r   r   r    r   r   r   r   r2   r   r   r   r   r   r$   r@   r   staticmethodry   r   rA   r"   r"   r<   r#   r   J  s    


	

fr   )r   rB   rL   ).r   dataclassesr   typingr   r   r   r   r   Ztorch.utils.checkpointr   Zactivationsr	   Z
generationr
   Zmodeling_flash_attention_utilsr   Zmodeling_outputsr   r   Zmodeling_utilsr   Zprocessing_utilsr   utilsr   r   r   r   r   autor   Zconfiguration_llavar   Z
get_loggerr   loggerr   r$   r   r*   rB   rL   r   r   __all__r"   r"   r"   r#   <module>   sF   
 ' " e