
    g4H                     @   d 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  ej        e          ZdZdZ ede           G d de                      ZdZ ede           G d dee
                      ZdS )zPyTorch Fuyu model.    )ListOptionalTupleUnionN)nn   )GenerationMixin)CausalLMOutputWithPast)PreTrainedModel)AutoModelForCausalLM)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )
FuyuConfigr   aI  
    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 ([`FuyuConfig`]):
            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.
zRThe bare Fuyu Model outputting raw hidden-states without any specific head on top.c                   (    e Zd ZeZdZdZg ZdZd Z	dS )FuyuPreTrainedModelfuyuTpast_key_valuesc                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Ng        )meanstd)configinitializer_range
isinstancer   Linearweightdatanormal_biaszero_	Embeddingpadding_idx)selfmoduler   s      b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/fuyu/modeling_fuyu.py_init_weightsz!FuyuPreTrainedModel._init_weights@   s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--    N)
__name__
__module____qualname__r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placementr(    r)   r'   r   r   5   sB        
 L&*#"3	? 	? 	? 	? 	?r)   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)
        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**.
        image_patches (`torch.FloatTensor` of shape `(batch_size, num_total_patches, patch_size_ x patch_size x num_channels)`, *optional*):
            Image patches to be used as continuous embeddings. The patches are flattened and then projected to the
            hidden size of the model.
        image_patches_indices (`torch.LongTensor` of shape `(batch_size, num_total_patches + number_of_newline_tokens + number_of_text_tokens, patch_size_ x patch_size x num_channels )`, *optional*):
            Indices indicating at which position the image_patches have to be inserted in input_embeds.
        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.
zpFuyu Model with a language modeling head on top for causal language model conditioned on image patches and text.c                   "    e Zd Zdef fdZd Zd Zd Zd Zd Z	d Z
d	 Zd
ej        deej                 dej        dej        fdZ ee           eee          	 	 	 	 	 	 	 	 	 	 	 	 ddej        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j                 dee         dee         dee         deeef         fd                        Z	 	 	 	 	 d dZ xZS )!FuyuForCausalLMr   c                 l   t                                          |           |j        | _        |j        j        | _        t          j        |j        |j                  | _	        t          j        |j        |j        z  |j        z  |j                  | _        d| _        |                                  d S )N)attn_implementationF)super__init__pad_token_idr$   text_config
vocab_sizer   from_config_attn_implementationlanguage_modelr   r   
patch_sizenum_channelshidden_sizevision_embed_tokensgradient_checkpointing	post_init)r%   r   	__class__s     r'   r8   zFuyuForCausalLM.__init__   s       !. ,72>F4O
 
 
 $&9 11F4GGI[$
 $
  ',#r)   c                 4    | j                                         S N)r>   get_input_embeddingsr%   s    r'   rH   z$FuyuForCausalLM.get_input_embeddings   s    "77999r)   c                 :    | j                             |           d S rG   )r>   set_input_embeddings)r%   values     r'   rK   z$FuyuForCausalLM.set_input_embeddings   s    0077777r)   c                 4    | j                                         S rG   )r>   get_output_embeddingsrI   s    r'   rN   z%FuyuForCausalLM.get_output_embeddings   s    "88:::r)   c                 :    | j                             |           d S rG   )r>   set_output_embeddings)r%   new_embeddingss     r'   rP   z%FuyuForCausalLM.set_output_embeddings   s    11.AAAAAr)   c                 :    | j                             |           d S rG   )r>   set_decoder)r%   decoders     r'   rS   zFuyuForCausalLM.set_decoder   s    ''00000r)   c                 4    | j                                         S rG   )r>   get_decoderrI   s    r'   rV   zFuyuForCausalLM.get_decoder       "..000r)   c                 4    | j                                         S rG   )r>   tie_weightsrI   s    r'   rY   zFuyuForCausalLM.tie_weights   rW   r)   word_embeddingscontinuous_embeddingsimage_patch_input_indicesreturnc           
      "   |j         d         t          |          k    s-t          dt          |          d|j         d                   |                                }t	          |j         d                   D ]}t          j        ||         dk    d          d         }||         |         }|j         d         ||         j         d         k    r)t          d||         j         d|j         d| d	          ||         |         |||f<   |S )
a  This function places the continuous_embeddings into the word_embeddings at the locations
        indicated by image_patch_input_indices. Different batch elements can have different numbers of continuous
        embeddings.

        Args:
            word_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Tensor of word embeddings.
            continuous_embeddings (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`):
                Tensor of continuous embeddings. The length of the list is the batch size. Each entry is shape
                [num_image_embeddings, hidden], and num_image_embeddings needs to match the number of non-negative
                indices in image_patch_input_indices for that batch element.
            image_patch_input_indices (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Tensor of indices of the image patches in the input_ids tensor.
        r   z7Batch sizes must match! Got len(continuous_embeddings)=z and word_embeddings.shape[0]=T)as_tuplezGNumber of continuous embeddings continuous_embeddings[batch_idx].shape=zA does not match number of continuous token ids src_indices.shape=z in batch element .)shapelen
ValueErrorclonerangetorchnonzero)r%   rZ   r[   r\   output_embeddings	batch_idxdst_indicessrc_indicess           r'   gather_continuous_embeddingsz,FuyuForCausalLM.gather_continuous_embeddings   se   (  %a(C0E,F,FFFls3H/I/IllQ`QfghQill   ,11334Q788 	f 	fI  -(A)(LPQ(Q\`aaabcdK 4I>{KK #&;I&F&LQ&OOO i7LY7W7] i i6A6Gi i\ei i i   9Ni8XYd8ei455  r)   )output_typer-   N	input_idsimage_patchesimage_patches_indicesattention_maskposition_idsr   inputs_embeds	use_cachelabelsoutput_attentionsoutput_hidden_statesreturn_dictc                     |
|
n j         j        }
||n j         j        }||n j         j        }||n j         j        }|t          d          ||j        \  }}nj        \  }}}nt          d          |}d}||d         d         j        d         }||z   }|J||j        nj        }t          j	        |||z   t          j
        |          }|                    d          }M  j                                        |          |)|' fd|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.text_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.text_config.vocab_size]`.

        Returns:

        Examples:

        ```python
        >>> from transformers import FuyuProcessor, FuyuForCausalLM
        >>> from PIL import Image
        >>> import requests

        >>> processor = FuyuProcessor.from_pretrained("adept/fuyu-8b")
        >>> model = FuyuForCausalLM.from_pretrained("adept/fuyu-8b")

        >>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> prompt = "Generate a coco-style caption.\n"

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

        >>> generated_ids = model.generate(**inputs, max_new_tokens=7)
        >>> generation_text = processor.batch_decode(generated_ids[:, -7:], skip_special_tokens=True)
        >>> print(generation_text[0])
        A blue bus parked on the side of a road.
        ```NzDYou cannot specify both input_ids and inputs_embeds at the same timez4You have to specify either input_is or inputs_embedsr      )dtypedevicec                     g | ]d}                     |                    j         j        j                                                d                               j                  eS )r   )rB   tor   r{   squeezer|   ).0patchrs   r%   s     r'   
<listcomp>z+FuyuForCausalLM.forward.<locals>.<listcomp>7  si     $ $ $  ,,UXXd6N6U6[-\-\]]WQZZR,--$ $ $r)   )rZ   r[   r\   )	rs   rq   rr   r   rv   rw   ru   rt   rx   )r   rv   rw   rt   use_return_dictrc   ra   r|   rf   arangelong	unsqueezer>   rH   rl   )r%   rn   ro   rp   rq   rr   r   rs   rt   ru   rv   rw   rx   
batch_size
seq_length_seq_length_with_pastpast_key_values_lengthr|   patch_embeddingsoutputss   `      `             r'   forwardzFuyuForCausalLM.forward   s   ` 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B] ]%>cddd"%._"J

&(5(;%J
AASTTT)!"&%4Q%7%:%@%C"#7:P#P )2)>Y%%MDXF <&
5K(KSXS]fl  L (11!44L FD/DDFFyQQM(_-D$ $ $ $ $ "/	$ $ $  !% A A$1*:.C !B ! ! %%')%+/!5# & 

 

 r)   c           	         |r|d d dd f         }|                     dd           }|g|e|                                                    d          dz
  }|                    |dk    d           |r|d d df                             d          }||d|i}	nd|i}	|||	d<   |	                    |||                     d          |||nd ||nd d	           |	S )
Nrr   r   r   rs   rn   rp   rt   )rr   r   rt   rq   rp   ro   )getr   cumsummasked_fill_r   update)
r%   rn   r   rq   rs   ro   rp   kwargsrr   model_inputss
             r'   prepare_inputs_for_generationz-FuyuForCausalLM.prepare_inputs_for_generationQ  s9     	*!!!!RSS&)Izz.$77%,*>)..0077;;a?L%%n&91=== A+AAArE2<<R@@ $)@+];LL'3L ,4IL01 ,#2#ZZ44"0BQBY)>)>_c2A2It 		
 		
 		
 r)   )NNNNNNNNNNNN)NNNNN)r*   r+   r,   r   r8   rH   rK   rN   rP   rS   rV   rY   rf   Tensorr   rl   r   FUYU_INPUTS_DOCSTRINGr   r
   _CONFIG_FOR_DOC
LongTensorr   FloatTensorboolr   r   r   r   __classcell__)rE   s   @r'   r4   r4      st       
z       : : :8 8 8; ; ;B B B1 1 11 1 11 1 1(!(!  $EL1(! $)<	(!
 
(! (! (! (!T +*+@AA+AP_``` '+&*.21537=A59$()-,0/3&*h h#h |h  %|	h
 !.h u/0h "$u'8"9:h   12h D>h &h $D>h 'tnh d^h 
u,,	-h h h a` BAhZ "* * * * * * * *r)   r4   ) __doc__typingr   r   r   r   rf   torch.utils.checkpointr   
generationr	   modeling_outputsr
   modeling_utilsr   models.auto.modeling_autor   utilsr   r   r   r   configuration_fuyur   
get_loggerr*   loggerr   FUYU_START_DOCSTRINGr   r   r4   r2   r)   r'   <module>r      s     / / / / / / / / / / / /            ) ) ) ) ) ) 6 6 6 6 6 6 - - - - - - = = = = = = t t t t t t t t t t t t * * * * * * 
	H	%	% " X ? ? ? ? ?/ ? ?	 ?&B J v f f f f f)? f f	 f f fr)   