Ë
    ÛÓ^j:;  ã                   ó:  — d 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	 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mZ ddlmZ  ej0                  e«      Ze G d„ de«      «       Z ed¬«       G d„ de«      «       Z ed¬«       G d„ dee«      «       Zg d¢Zy)zPyTorch Fuyu model.é    N)Únné   )ÚCache)ÚGenerationMixin)ÚBaseModelOutputWithPoolingÚCausalLMOutputWithPast)ÚPreTrainedModel)Ú	AutoModel)ÚUnpack)ÚTransformersKwargsÚauto_docstringÚcan_return_tupleÚloggingÚtorch_compilable_checké   )Ú
FuyuConfigc                   ó>   — e Zd ZU eed<   dZdZdZdZdZ	dZ
dZg ZdgZy)ÚFuyuPreTrainedModelÚconfigÚmodel)ÚimageÚtextTÚpast_key_valuesN)Ú__name__Ú
__module__Ú__qualname__r   Ú__annotations__Úbase_model_prefixÚinput_modalitiesÚsupports_gradient_checkpointingÚ_supports_attention_backendÚ_supports_flash_attnÚ_supports_sdpaÚ_supports_flex_attnÚ_no_split_modulesÚ_skip_keys_device_placement© ó    úq/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/fuyu/modeling_fuyu.pyr   r       s@   … àÓØÐØ(ÐØ&*Ð#Ø"&ÐØÐØ€NØÐØÐØ#4Ð"5Ñr(   r   zt
    The Fuyu model which consists of a vision backbone and a language model, without a language modeling head.
    )Úcustom_introc                   ó4  ‡ — e Zd Zdefˆ fd„Zdej                  deej                     dej                  dej                  fd„Ze	e
dej                  d	ee   deez  fd
„«       «       Zdej"                  dej                  dej                  fd„Ze	e
	 	 	 	 	 	 	 	 ddej"                  dz  dej                  dz  dej                  dz  dej                  dz  dej"                  dz  dedz  dej                  dz  dedz  d	ee   deez  fd„«       «       Zˆ xZS )Ú	FuyuModelr   c                 ó„  •— t         ‰| �  |«       |j                  | _        |j                  j
                  | _        t        j                  |j                  «      | _        t        j                  |j                  |j                  z  |j                  z  |j                  «      | _        d| _        | j!                  «        y )NF)ÚsuperÚ__init__Úpad_token_idÚpadding_idxÚtext_configÚ
vocab_sizer
   Úfrom_configÚlanguage_modelr   ÚLinearÚ
patch_sizeÚnum_channelsÚhidden_sizeÚvision_embed_tokensÚgradient_checkpointingÚ	post_init©Úselfr   Ú	__class__s     €r)   r/   zFuyuModel.__init__4   s–   ø€ Ü‰Ñ˜Ô Ø!×.Ñ.ˆÔØ ×,Ñ,×7Ñ7ˆŒÜ'×3Ñ3°F×4FÑ4FÓGˆÔÜ#%§9¡9Ø×Ñ × 1Ñ 1Ñ1°F×4GÑ4GÑGÈ×I[ÑI[ó$
ˆÔ ð ',ˆÔ#à�‰Õr(   Úword_embeddingsÚcontinuous_embeddingsÚimage_patch_input_indicesÚreturnc           
      ó  — |j                   d   t        |«      k(  s't        dt        |«      ›d|j                   d   ›�«      ‚|j                  «       }t	        |j                   d   «      D ]ž  }t        j                  ||   dk\  d¬«      d   }||   |   }|j                   d   ||   j                   d   kD  r,t        d||   j                   ›d|j                   ›d|› d	�«      ‚||   |   j                  |j                  «      |||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ÚtoÚdevice)r>   r@   rA   rB   Úoutput_embeddingsÚ	batch_idxÚdst_indicesÚsrc_indicess           r)   Úgather_continuous_embeddingsz&FuyuModel.gather_continuous_embeddingsA   sZ  € ð(  ×%Ñ% aÑ(¬CÐ0EÓ,FÒFÜØJ¬sÐ3HÓ/IÐ.KÐKjÐQ`×QfÑQfÐghÑQiÐPkÐlóð ð ,×1Ñ1Ó3ÐÜ˜×4Ñ4°QÑ7Ó8ò 	ˆIô  Ÿ-™-Ð(AÀ)Ñ(LÐPQÑ(QÐ\`ÔaÐbcÑdˆKð 4°IÑ>¸{ÑKˆKà× Ñ  Ñ#Ð&;¸IÑ&F×&LÑ&LÈQÑ&OÒOÜ Ø^Ð7LÈYÑ7W×7]Ñ7]Ð6_ð `IØ6A×6GÑ6GÐ5IÐI[Ð\eÐ[fÐfgðióð ð 9NÈiÑ8XÐYdÑ8e×8hÑ8hØ!×(Ñ(ó9Ð˜i¨Ð4Ò5ð	ð  !Ð r(   Úpixel_valuesÚkwargsc                 ó<   — | j                  |«      }t        |¬«      S )z®
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The tensors corresponding to the input images.
        )Úlast_hidden_state)r:   r   )r>   rU   rV   Úpatch_embeddingss       r)   Úget_image_featureszFuyuModel.get_image_featuresm   s!   € ð  ×3Ñ3°LÓAÐÜ)Ð<LÔMÐMr(   Ú	input_idsÚinputs_embedsÚimage_featuresc                 ó.  — |€m| | j                  «       t        j                  | j                  j                  t        j
                  |j                  ¬«      «      k(  }|j                  d«      }n|| j                  j                  k(  }|j                  «       }|j                  d   |j                  d   z  }|j                  d«      j                  |j                  «      }t        ||j                  d   z  |j                  «       k(  d|› d|› �«       |S )zï
        Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
        equal to the length of multimodal features. If the lengths are different, an error is raised.
        ©ÚdtyperO   éÿÿÿÿr   r   z6Image features and image tokens do not match, tokens: z, features: )Úget_input_embeddingsrL   Útensorr   Úimage_token_idÚlongrO   ÚallÚsumrG   Ú	unsqueezerN   r   Únumel)r>   r[   r\   r]   Úspecial_image_maskÚn_image_tokensÚn_image_featuress          r)   Úget_placeholder_maskzFuyuModel.get_placeholder_masky   s  € ð ÐØ!.Ð2M°$×2KÑ2KÓ2MÜ—‘˜TŸ[™[×7Ñ7¼u¿z¹zÐR_×RfÑRfÔgó3ñ "Ðð "4×!7Ñ!7¸Ó!;Ñà!*¨d¯k©k×.HÑ.HÑ!HÐà+×/Ñ/Ó1ˆØ)×/Ñ/°Ñ2°^×5IÑ5IÈ!Ñ5LÑLÐØ/×9Ñ9¸"Ó=×@Ñ@À×AUÑAUÓVÐÜØ˜]×0Ñ0°Ñ4Ñ4¸×8LÑ8LÓ8NÑNØDÀ^ÐDTÐT`ÐaqÐ`rÐsô	
ð "Ð!r(   NÚimage_patchesÚimage_patches_indicesÚattention_maskÚposition_idsr   Ú	use_cachec	           	      ól  — |du |duz  rt        d«      ‚|€  | j                  j                  «       |«      }|j                  d   }
|€i|�|j                  n|j                  }|�|j                  «       nd}t        j                  ||
|z   t        j                  |¬«      }|j                  d«      }|�i| j                  |d¬«      j                  }|j                  |j                  |j                  «      }| j                  |||¬«      }|j                  ||«      } | j                  d
|||||d	œ|	¤Ž}|S )aä  
        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, sequence_length)`, *optional*):
            Tensor of indices of the image patches in the input_ids tensor.
        Nz:You must specify exactly one of input_ids or inputs_embedsr   r   r_   T)Úreturn_dict)r\   r]   )r\   rp   rq   r   rr   r'   )rI   r5   rb   rG   rO   Úget_seq_lengthrL   Úarangere   rh   rZ   rX   rN   r`   rm   Úmasked_scatter)r>   r[   rn   ro   rp   rq   r   r\   rr   rV   Úseq_lenrO   Úpast_key_values_lengthrY   rj   Úoutputss                   r)   ÚforwardzFuyuModel.forward‘   sl  € ð, ˜Ð -°tÐ";Ò<ÜÐYÓZÐZàÐ ØF˜D×/Ñ/×DÑDÓFÀyÓQˆMà×%Ñ% aÑ(ˆàÐØ)2Ð)>�Y×%Ò%ÀM×DXÑDXˆFØIXÐId _×%CÑ%CÔ%EÐjkÐ"Ü Ÿ<™<Ø&¨Ð2HÑ(HÔPU×PZÑPZÐciôˆLð (×1Ñ1°!Ó4ˆLàÐ$Ø#×6Ñ6°}ÐRVÐ6ÓW×iÑiÐØ/×2Ñ2°=×3GÑ3GÈ×I\ÑI\Ó]ÐØ!%×!:Ñ!:Ø¨ÐGWð ";ó "Ðð *×8Ñ8Ð9KÐM]Ó^ˆMà%�$×%Ñ%ð 
Ø'Ø)Ø%Ø+Øñ
ð ñ
ˆð ˆr(   )NNNNNNNN)r   r   r   r   r/   rL   ÚTensorÚlistrT   r   r   ÚFloatTensorr   r   Útupler   rZ   Ú
LongTensorrm   r   Úboolr   r{   Ú__classcell__©r?   s   @r)   r,   r,   .   s²  ø„ ð˜zõ ð*!àŸ™ð*!ð  $ E§L¡LÑ1ð*!ð $)§<¡<ð	*!ð
 
�‰ó*!ðX ØðNØ!×-Ñ-ðNØ9?Ð@RÑ9SðNà	Ð+Ñ	+òNó ó ðNð"Ø×)Ñ)ð"Ø:?×:KÑ:Kð"Ø]b×]nÑ]nó"ð0 Øð .2à-1Ø59Ø.2Ø04Ø(,Ø26Ø!%ñ5à×#Ñ# dÑ*ð5ð —|‘| dÑ*ð	5ð
  %Ÿ|™|¨dÑ2ð5ð Ÿ™ tÑ+ð5ð ×&Ñ&¨Ñ-ð5ð  ™ð5ð ×(Ñ(¨4Ñ/ð5ð ˜$‘;ð5ð Ð+Ñ,ð5ð 
Ð'Ñ	'ò5ó ó ô5r(   r,   zz
    Fuyu Model with a language modeling head on top for causal language model conditioned on image patches and text.
    c                   óz  ‡ — e Zd ZddiZdefˆ fd„Zee	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dedz  dej                  dz  dedz  dej                  dz  dedz  dee   deez  fd„«       «       Z	 	 	 	 	 	 dˆ fd„	Zˆ xZS )ÚFuyuForCausalLMzlm_head.weightz(model.language_model.embed_tokens.weightr   c                 óî   •— t         ‰| �  |«       t        |«      | _        t	        j
                  |j                  j                  |j                  j                  d¬«      | _	        | j                  «        y )NF)Úbias)r.   r/   r,   r   r   r6   r2   r9   r3   Úlm_headr<   r=   s     €r)   r/   zFuyuForCausalLM.__init__Ó   sS   ø€ Ü‰Ñ˜Ô Ü˜vÓ&ˆŒ
Ü—y‘y ×!3Ñ!3×!?Ñ!?À×ASÑAS×A^ÑA^ÐejÔkˆŒØ�‰Õr(   Nr[   rn   ro   rp   rq   r   r\   rr   ÚlabelsÚlogits_to_keeprV   rC   c                 ó‚  —  | j                   d||||||||dœ|¤Ž}|d   }t        |
t        «      rt        |
 d«      n|
}| j	                  |dd…|dd…f   «      }d}|	�4 | j
                  d||	| j                  j                  j                  dœ|¤Ž}t        |||j                  |j                  |j                  ¬«      S )a‘  
        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, sequence_length)`, *optional*):
            Tensor of indices of the image patches in the input_ids tensor.
        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]`.

        Examples:

        ```python
        >>> from transformers import FuyuProcessor, FuyuForCausalLM
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO

        >>> 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"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))
        >>> 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.
        ```)r[   rn   ro   r\   rp   rq   r   rr   r   N)Úlogitsr‰   r3   )ÚlossrŒ   r   Úhidden_statesÚ
attentionsr'   )r   Ú
isinstanceÚintÚslicerˆ   Úloss_functionr   r2   r3   r   r   rŽ   r�   )r>   r[   rn   ro   rp   rq   r   r\   rr   r‰   rŠ   rV   rz   rŽ   Úslice_indicesrŒ   r�   s                    r)   r{   zFuyuForCausalLM.forwardÙ   sí   € ðj �$—*‘*ð 

ØØ'Ø"7Ø'Ø)Ø%Ø+Øñ

ð ñ

ˆð   ™
ˆä8BÀ>ÔSVÔ8Wœ˜~˜o¨tÔ4Ð]kˆØ—‘˜mªA¨}ºaÐ,?Ñ@ÓAˆàˆØÐØ%�4×%Ñ%ð Ø f¸¿¹×9PÑ9P×9[Ñ9[ñØ_eñˆDô &ØØØ#×3Ñ3Ø!×/Ñ/Ø×)Ñ)ô
ð 	
r(   c           
      ór   •— t        ‰
| �  |f||||||dœ|¤Ž}	|s|j                  dd«      r
d |	d<   d |	d<   |	S )N)r   rp   r\   rn   ro   Úis_first_iterationrr   Tro   rn   )r.   Úprepare_inputs_for_generationÚget)r>   r[   r   rp   r\   rn   ro   r–   rV   Úmodel_inputsr?   s             €r)   r—   z-FuyuForCausalLM.prepare_inputs_for_generation-  se   ø€ ô ‘wÑ<Øð	
à+Ø)Ø'Ø'Ø"7Ø1ñ	
ð ñ	
ˆñ " f§j¡j°¸dÔ&Cà48ˆLÐ0Ñ1Ø,0ˆL˜Ñ)àÐr(   )
NNNNNNNNNr   )NNNNNF)r   r   r   Ú_tied_weights_keysr   r/   r   r   rL   r€   r|   r   r~   r�   r‘   r   r   r   r   r{   r—   r‚   rƒ   s   @r)   r…   r…   Ë   sY  ø„ ð +Ð,VÐWÐð˜zõ ð Øð .2à-1Ø59Ø.2Ø04Ø(,Ø26Ø!%Ø&*Ø%&ñP
à×#Ñ# dÑ*ðP
ð —|‘| dÑ*ð	P
ð
  %Ÿ|™|¨dÑ2ðP
ð Ÿ™ tÑ+ðP
ð ×&Ñ&¨Ñ-ðP
ð  ™ðP
ð ×(Ñ(¨4Ñ/ðP
ð ˜$‘;ðP
ð —‘˜tÑ#ðP
ð ˜d™
ðP
ð Ð+Ñ,ðP
ð 
Ð'Ñ	'òP
ó ó ðP
ðj ØØØØ"Ø ÷ñ r(   r…   )r…   r   r,   )Ú__doc__rL   r   Úcache_utilsr   Ú
generationr   Úmodeling_outputsr   r   Úmodeling_utilsr	   Úmodels.auto.modeling_autor
   Úprocessing_utilsr   Úutilsr   r   r   r   r   Úconfiguration_fuyur   Ú
get_loggerr   Úloggerr   r,   r…   Ú__all__r'   r(   r)   ú<module>r§      s¸   ðñ ã Ý å  Ý )ß RÝ -Ý 2Ý &ß jÕ jÝ *ð 
ˆ×	Ñ	˜HÓ	%€ð ô
6˜/ó 
6ó ð
6ñ ðôô
UÐ#ó Uóð
Uñp ðôô
zÐ)¨?ó zóð
zòz B�r(   