Ë
    S^(háI  ã                   óB  — d Z ddlZddlmZ ddlmZmZ ddlmZmZ ddl	m
Z
 ddlmZmZmZmZ  ej                   e«      Zd	Z G d
„ dej(                  «      ZdZdZ ede«       G d„ dej(                  e
«      «       Z edee«       G d„ dej(                  «      «       Zy)zPyTorch MMBT model.é    N)Únn)ÚCrossEntropyLossÚMSELossé   )ÚBaseModelOutputWithPoolingÚSequenceClassifierOutput)ÚModuleUtilsMixin)Úadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsÚ
MMBTConfigc                   ó*   ‡ — e Zd ZdZˆ fd„Zdd„Zˆ xZS )ÚModalEmbeddingszPGeneric Modal Embeddings which takes in an encoder, and a transformer embedding.c                 ón  •— t         ‰| �  «        || _        || _        t	        j
                  |j                  |j                  «      | _        |j                  | _	        |j                  | _
        |j                  | _        |j                  | _        t	        j                  |j                  ¬«      | _        y )N)Úp)ÚsuperÚ__init__ÚconfigÚencoderr   ÚLinearÚmodal_hidden_sizeÚhidden_sizeÚproj_embeddingsÚposition_embeddingsÚtoken_type_embeddingsÚword_embeddingsÚ	LayerNormÚDropoutÚhidden_dropout_probÚdropout)Úselfr   r   Ú
embeddingsÚ	__class__s       €úo/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/modeling_mmbt.pyr   zModalEmbeddings.__init__#   sˆ   ø€ Ü‰ÑÔØˆŒØˆŒÜ!Ÿy™y¨×)AÑ)AÀ6×CUÑCUÓVˆÔØ#-×#AÑ#AˆÔ Ø%/×%EÑ%EˆÔ"Ø)×9Ñ9ˆÔØ#×-Ñ-ˆŒÜ—z‘z F×$>Ñ$>Ô?ˆ�ó    c                 óJ  — | j                  | j                  |«      «      }|j                  d«      }|�>| j                  |«      }|dz  }t	        j
                  |j                  d«      |gd¬«      }|�>| j                  |«      }	|dz  }t	        j
                  ||	j                  d«      gd¬«      }|€`t	        j                  |t        j                  |j                  ¬«      }|j                  d«      j                  |j                  d«      |«      }|€At	        j                  |j                  d«      |ft        j                  |j                  ¬«      }| j                  |«      }
| j                  |«      }||
z   |z   }| j                  |«      }| j                  |«      }|S )Né   ©Údim©ÚdtypeÚdevicer   )r   r   Úsizer   ÚtorchÚcatÚ	unsqueezeÚarangeÚlongr-   ÚexpandÚzerosr   r   r   r!   )r"   Úinput_modalÚstart_tokenÚ	end_tokenÚposition_idsÚtoken_type_idsÚtoken_embeddingsÚ
seq_lengthÚstart_token_embedsÚend_token_embedsr   r   r#   s                r%   ÚforwardzModalEmbeddings.forward.   sŒ  € Ø×/Ñ/°·±¸[Ó0IÓJÐØ%×*Ñ*¨1Ó-ˆ
àÐ"Ø!%×!5Ñ!5°kÓ!BÐØ˜!‰OˆJÜ$Ÿy™yÐ*<×*FÑ*FÀqÓ*IÐK[Ð)\ÐbcÔdÐàÐ Ø#×3Ñ3°IÓ>ÐØ˜!‰OˆJÜ$Ÿy™yÐ*:Ð<L×<VÑ<VÐWXÓ<YÐ)ZÐ`aÔbÐàÐÜ Ÿ<™<¨
¼%¿*¹*È[×M_ÑM_Ô`ˆLØ'×1Ñ1°!Ó4×;Ñ;¸K×<LÑ<LÈQÓ<OÐQ[Ó\ˆLàÐ!Ü"Ÿ[™[Ø×!Ñ! !Ó$ jÐ1¼¿¹ÈK×L^ÑL^ôˆNð #×6Ñ6°|ÓDÐØ $× :Ñ :¸>Ó JÐØ%Ð(;Ñ;Ð>SÑSˆ
Ø—^‘^ JÓ/ˆ
Ø—\‘\ *Ó-ˆ
ØÐr&   )NNNN©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r?   Ú__classcell__©r$   s   @r%   r   r       s   ø„ ÙZô	@÷r&   r   aÀ  
    MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and
    Text](https://github.com/facebookresearch/mmbt) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.
    It's a supervised multimodal bitransformer model that fuses information from text and other image encoders, and
    obtain state-of-the-art performance on various multimodal classification benchmark tasks.

    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 ([`MMBTConfig`]): 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.
        transformer (`nn.Module`): A text transformer that is used by MMBT.
            It should have embeddings, encoder, and pooler attributes.
        encoder (`nn.Module`): Encoder for the second modality.
            It should take in a batch of modal inputs and return k, n dimension embeddings.
a4  
    Args:
        input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`):
            The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image
            Encoder, the shape would be (batch_size, channels, height, width)
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it's
            appended to the end of other modality embeddings. Indices can be obtained using [`AutoTokenizer`]. See
            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification
            tasks.
        modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used.
        attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`:
            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)
        token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`:
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`:
            Segment token indices to indicate different portions of the non-text modality. The embeddings from these
            tokens will be summed with the respective token embeddings for the non-text modality.
        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.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings for the non-text modality.
            Selected in the range `[0, config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *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.
        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**.

        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.
zRThe bare MMBT Model outputting raw hidden-states without any specific head on top.c                   ó€   ‡ — e Zd Zˆ fd„Z ee«       eee¬«      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       «       Z	d„ Z
d„ Zˆ xZS )Ú	MMBTModelc                 óv   •— t         ‰| �  «        || _        || _        t	        |||j
                  «      | _        y ©N)r   r   r   Útransformerr   r#   Úmodal_encoder©r"   r   rK   r   r$   s       €r%   r   zMMBTModel.__init__µ   s4   ø€ Ü‰ÑÔØˆŒØ&ˆÔÜ,¨V°W¸k×>TÑ>TÓUˆÕr&   )Úoutput_typeÚconfig_classc           
      óB  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|�|�t	        d«      ‚|�|j                  «       }n!|�|j                  «       dd }nt	        d«      ‚|�|j                  n|j                  }| j                  ||||	|¬«      }|j                  «       dd }|€&t        j                  |t        j                  |¬«      }| j                  j                  ||||¬«      }t        j                  ||gd«      }|j                  «       dd }|€t        j                  ||¬	«      }n=t        j                  t        j                  ||t        j                  ¬
«      |gd¬«      }|€t        j                  ||¬	«      }n.t        j                  t        j                  ||¬	«      |gd¬«      }| j                  ||«      }| j                  |«      }| j!                  |
| j                   j"                  «      }
| j                  j%                  |||
|||||¬«      }|d   }| j                  j'                  |«      }|s
||f|dd z   S t)        |||j*                  |j,                  ¬«      S )a  
        Returns:

        Examples:

        ```python
        # For example purposes. Not runnable.
        transformer = BertModel.from_pretrained("google-bert/bert-base-uncased")
        encoder = ImageEncoder(args)
        mmbt = MMBTModel(config, transformer, encoder)
        ```NzDYou cannot specify both input_ids and inputs_embeds at the same timeéÿÿÿÿz5You have to specify either input_ids or inputs_embeds)r7   r8   r9   r:   r+   )Ú	input_idsr9   r:   Úinputs_embedsr(   )r-   )r-   r,   r)   )Úattention_maskÚ	head_maskÚencoder_hidden_statesÚencoder_attention_maskÚoutput_attentionsÚoutput_hidden_statesÚreturn_dictr   )Úlast_hidden_stateÚpooler_outputÚhidden_statesÚ
attentions)r   rX   rY   Úuse_return_dictÚ
ValueErrorr.   r-   rL   r/   Úonesr3   rK   r#   r0   Úget_extended_attention_maskÚinvert_attention_maskÚget_head_maskÚnum_hidden_layersr   Úpoolerr   r]   r^   )r"   r6   rR   Úmodal_start_tokensÚmodal_end_tokensrT   r:   Úmodal_token_type_idsr9   Úmodal_position_idsrU   rS   rV   rW   rX   rY   rZ   Úinput_txt_shaper-   Úmodal_embeddingsÚinput_modal_shapeÚtxt_embeddingsÚembedding_outputÚinput_shapeÚextended_attention_maskÚencoder_extended_attention_maskÚencoder_outputsÚsequence_outputÚpooled_outputs                                r%   r?   zMMBTModel.forward»   sÂ  € ð@ 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆàÐ  ]Ð%>ÜÐcÓdÐdØÐ"Ø'Ÿn™nÓ.‰OØÐ&Ø+×0Ñ0Ó2°3°BÐ7‰OäÐTÓUÐUà%.Ð%:�×!Ò!À×@TÑ@Tˆà×-Ñ-ØØ*Ø&Ø+Ø/ð .ó 
Ðð -×1Ñ1Ó3°C°RÐ8ÐàÐ!Ü"ŸZ™Z¨¼u¿z¹zÐRXÔYˆNà×)Ñ)×4Ñ4Ø¨lÈ>Ðivð 5ó 
ˆô !Ÿ9™9Ð&6¸Ð%GÈÓKÐà&×+Ñ+Ó-¨c¨rÐ2ˆàÐ!Ü"ŸZ™Z¨¸FÔC‰Nä"ŸY™YÜ—‘Ð-°fÄEÇJÁJÔOÐQ_Ð`ÐfgôˆNð "Ð)Ü%*§Z¡Z°ÀFÔ%KÑ"ä%*§Y¡YÜ—‘Ð-°fÔ=Ð?UÐVÐ\]ô&Ð"ð #'×"BÑ"BÀ>ÐS^Ó"_ÐØ*.×*DÑ*DÐE[Ó*\Ð'Ø×&Ñ& y°$·+±+×2OÑ2OÓPˆ	à×*Ñ*×2Ñ2ØØ2ØØ"7Ø#BØ/Ø!5Ø#ð 3ó 	
ˆð *¨!Ñ,ˆØ×(Ñ(×/Ñ/°Ó@ˆáØ# ]Ð3°oÀaÀbÐ6IÑIÐIä)Ø-Ø'Ø)×7Ñ7Ø&×1Ñ1ô	
ð 	
r&   c                 ó.   — | j                   j                  S rJ   ©r#   r   )r"   s    r%   Úget_input_embeddingszMMBTModel.get_input_embeddings*  s   € Ø�‰×.Ñ.Ð.r&   c                 ó&   — || j                   _        y rJ   rw   )r"   Úvalues     r%   Úset_input_embeddingszMMBTModel.set_input_embeddings-  s   € Ø*/ˆ�‰Õ'r&   )NNNNNNNNNNNNNNN)rA   rB   rC   r   r   ÚMMBT_INPUTS_DOCSTRINGr   r   Ú_CONFIG_FOR_DOCr?   rx   r{   rE   rF   s   @r%   rH   rH   °   sr   ø„ ô
Vñ +Ð+@ÓAÙÐ+EÐTcÔdð ØØØØØ!ØØØØØ"Ø#ØØ!Øò#k
ó eó Bðk
òZ/ö0r&   rH   zw
    MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
    c                   óB   ‡ — e Zd ZdZˆ fd„Z	 	 	 	 	 	 	 	 	 	 	 	 dd„Zˆ xZS )ÚMMBTForClassificationa  
    **labels**: (*optional*) `torch.LongTensor` of shape `(batch_size,)`:
        Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
        config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
        `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

    Returns: *Tuple* comprising various elements depending on the configuration (config) and inputs: **loss**:
    (*optional*, returned when `labels` is provided) `torch.FloatTensor` of shape `(1,)`: Classification (or
    regression if config.num_labels==1) loss. **logits**:
        `torch.FloatTensor` of shape `(batch_size, config.num_labels)` Classification (or regression if
        config.num_labels==1) scores (before SoftMax).
    **hidden_states**: (*optional*, returned when `output_hidden_states=True`) list of `torch.FloatTensor` (one for
    the output of each layer + the output of the embeddings) of shape `(batch_size, sequence_length, hidden_size)`:
    Hidden-states of the model at the output of each layer plus the initial embedding outputs. **attentions**:
    (*optional*, returned when `output_attentions=True`) list 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.

    Examples:

    ```python
    # For example purposes. Not runnable.
    transformer = BertModel.from_pretrained("google-bert/bert-base-uncased")
    encoder = ImageEncoder(args)
    model = MMBTForClassification(config, transformer, encoder)
    outputs = model(input_modal, input_ids, labels=labels)
    loss, logits = outputs[:2]
    ```c                 ó  •— t         ‰| �  «        |j                  | _        t        |||«      | _        t        j                  |j                  «      | _        t        j                  |j                  |j                  «      | _        y rJ   )r   r   Ú
num_labelsrH   Úmmbtr   r   r    r!   r   r   Ú
classifierrM   s       €r%   r   zMMBTForClassification.__init__V  s_   ø€ Ü‰ÑÔØ ×+Ñ+ˆŒä˜f k°7Ó;ˆŒ	Ü—z‘z &×"<Ñ"<Ó=ˆŒÜŸ)™) F×$6Ñ$6¸×8IÑ8IÓJˆ�r&   c                 ó0  — |�|n| j                   j                  }| j                  |||||||||	|
||¬«      }|d   }| j                  |«      }| j	                  |«      }d }|�}| j
                  dk(  r2t        «       } ||j                  d«      |j                  d«      «      }n<t        «       } ||j                  d| j
                  «      |j                  d«      «      }|s|f|dd  z   }|�|f|z   S |S t        |||j                  |j                  ¬«      S )N)r6   rR   rg   rh   rT   r:   ri   r9   rj   rU   rS   rZ   r(   rQ   é   )ÚlossÚlogitsr]   r^   )r   r_   r‚   r!   rƒ   r�   r   Úviewr   r   r]   r^   )r"   r6   rR   rg   rh   rT   r:   ri   r9   rj   rU   rS   ÚlabelsrZ   Úoutputsru   r‡   r†   Úloss_fctÚoutputs                       r%   r?   zMMBTForClassification.forward^  s.  € ð  &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà—)‘)Ø#ØØ1Ø-Ø)Ø)Ø!5Ø%Ø1ØØ'Ø#ð ó 
ˆð   ™
ˆàŸ™ ]Ó3ˆØ—‘ Ó/ˆàˆØÐØ�‰ !Ò#ä"›9�Ù §¡¨B£°·±¸R³ÓA‘ä+Ó-�Ù §¡¨B°·±Ó @À&Ç+Á+ÈbÃ/ÓR�áØ�Y ¨¨ Ñ,ˆFØ)-Ð)9�T�G˜fÑ$ÐE¸vÐEä'ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r&   )NNNNNNNNNNNNr@   rF   s   @r%   r   r   1  s9   ø„ ñô:Kð ØØØØØ!ØØØØØØ÷9
r&   r   )rD   r/   r   Útorch.nnr   r   Úmodeling_outputsr   r   Úmodeling_utilsr	   Úutilsr
   r   r   r   Ú
get_loggerrA   Úloggerr}   ÚModuler   ÚMMBT_START_DOCSTRINGr|   rH   r   © r&   r%   ú<module>r–      sÀ   ðñ  ã Ý ß .ç UÝ /ß uÓ uð 
ˆ×	Ñ	˜HÓ	%€à€ô*�b—i‘iô *ðZÐ ð0HÐ ñV ØXØóôz0�—	‘	Ð+ó z0ó	ðz0ñz ðð Øóô_
˜BŸI™Ió _
óñ_
r&   