Ë
    T^(hV*  ã                   óø   — d dl mZ d dl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mZ dd	lmZ d
dlmZ ddlmZ dZdZ ej2                  e«      ZdZe G d„ de«      «       Z G d„ de«      ZdgZy)é    )Ú	dataclass)ÚListÚOptionalÚUnionNé   )ÚCache)Ú$ImageClassifierOutputWithNoAttention)ÚPreTrainedModel)Ú%add_start_docstrings_to_model_forwardÚlogging)Údeprecate_kwargé   )ÚAutoModelForImageTextToTexté   )ÚShieldGemma2Configzgoogle/shieldgemma-2-4b-itr   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 `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 (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - 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)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `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.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   ó:   — e Zd ZU dZdZeej                     ed<   y)Ú0ShieldGemma2ImageClassifierOutputWithNoAttentionz^ShieldGemma2 classifies imags as violative or not relative to a specific policy
    Args:
    NÚprobabilities)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   ÚtorchÚTensorÚ__annotations__© ó    út/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/shieldgemma2/modeling_shieldgemma2.pyr   r   r   s   … ñð -1€M�8˜EŸL™LÑ)Ô0r   r   c            !       ó  ‡ — e Zd ZeZdefˆ fd„Zd„ Zd„ Zd„ Zd„ Z	d„ Z
d„ Zd	„ Z ed
dd¬«       ee«      	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddeej$                     deej&                     deej(                     deej$                     deeeej&                     ef      deej$                     deej$                     deej&                     deej$                     dee   dee   dee   dee   deeej(                  f   defd„«       «       Zˆ xZS )Ú"ShieldGemma2ForImageClassificationÚconfigc                 ó¤   •— t         ‰| �  |¬«       t        |dd«      | _        t        |dd«      | _        t        j                  |¬«      | _        y )N)r!   Úyes_token_indexi *  Úno_token_indexi»  )ÚsuperÚ__init__Úgetattrr#   r$   r   Úfrom_configÚmodel)Úselfr!   Ú	__class__s     €r   r&   z+ShieldGemma2ForImageClassification.__init__~   sI   ø€ Ü‰Ñ ÐÔ'Ü& vÐ/@À&ÓIˆÔÜ% fÐ.>ÀÓEˆÔÜ0×<Ñ<ÀFÔKˆ�
r   c                 óJ   — | j                   j                  j                  «       S ©N)r)   Úlanguage_modelÚget_input_embeddings©r*   s    r   r/   z7ShieldGemma2ForImageClassification.get_input_embeddings„   s   € Ø�z‰z×(Ñ(×=Ñ=Ó?Ð?r   c                 óN   — | j                   j                  j                  |«       y r-   )r)   r.   Úset_input_embeddings)r*   Úvalues     r   r2   z7ShieldGemma2ForImageClassification.set_input_embeddings‡   s   € Ø�
‰
×!Ñ!×6Ñ6°uÕ=r   c                 óJ   — | j                   j                  j                  «       S r-   )r)   r.   Úget_output_embeddingsr0   s    r   r5   z8ShieldGemma2ForImageClassification.get_output_embeddingsŠ   s   € Ø�z‰z×(Ñ(×>Ñ>Ó@Ð@r   c                 óN   — | j                   j                  j                  |«       y r-   )r)   r.   Úset_output_embeddings)r*   Únew_embeddingss     r   r7   z8ShieldGemma2ForImageClassification.set_output_embeddings�   s   € Ø�
‰
×!Ñ!×7Ñ7¸ÕGr   c                 óN   — | j                   j                  j                  |«       y r-   )r)   r.   Úset_decoder)r*   Údecoders     r   r:   z.ShieldGemma2ForImageClassification.set_decoder�   s   € Ø�
‰
×!Ñ!×-Ñ-¨gÕ6r   c                 óJ   — | j                   j                  j                  «       S r-   )r)   r.   Úget_decoderr0   s    r   r=   z.ShieldGemma2ForImageClassification.get_decoder“   ó   € Ø�z‰z×(Ñ(×4Ñ4Ó6Ð6r   c                 óJ   — | j                   j                  j                  «       S r-   )r)   r.   Útie_weightsr0   s    r   r@   z.ShieldGemma2ForImageClassification.tie_weights–   r>   r   Únum_logits_to_keepz4.50Úlogits_to_keep)ÚversionÚnew_nameÚ	input_idsÚpixel_valuesÚattention_maskÚposition_idsÚpast_key_valuesÚtoken_type_idsÚcache_positionÚinputs_embedsÚlabelsÚ	use_cacheÚoutput_attentionsÚoutput_hidden_statesÚreturn_dictÚreturnc                 óä   —  | j                   d|||||||||	|
||||dœ|¤Ž}|j                  }|dd…d| j                  | j                  gf   }t	        j
                  |d¬«      }t        ||¬«      S )a§  Predicts the binary probability that the image violates the specified policy.

        Returns:
            A `ShieldGemma2ImageClassifierOutputWithNoAttention` instance containing the logits and probabilities
            associated with the model predicting the `Yes` or `No` token as the response to that prompt, captured in the
            following properties.

                *   `logits` (`torch.Tensor` of shape `(batch_size, 2)`):
                    The first position along dim=1 is the logits for the `Yes` token and the second position along dim=1 is
                    the logits for the `No` token.
                *   `probabilities` (`torch.Tensor` of shape `(batch_size, 2)`):
                    The first position along dim=1 is the probability of predicting the `Yes` token and the second position
                    along dim=1 is the probability of predicting the `No` token.

            ShieldGemma prompts are constructed such that predicting the `Yes` token means the content *does violate* the
            policy as described. If you are only interested in the violative condition, use
            `violated = outputs.probabilities[:, 1]` to extract that slice from the output tensors.

            When used with the `ShieldGemma2Processor`, the `batch_size` will be equal to `len(images) * len(policies)`,
            and the order within the batch will be img1_policy1, ... img1_policyN, ... imgM_policyN.
        )rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rB   Néÿÿÿÿ)Údim)Úlogitsr   r   )r)   rV   r#   r$   r   Úsoftmaxr   )r*   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rB   Ú	lm_kwargsÚoutputsrV   Úselected_logitsr   s                       r   Úforwardz*ShieldGemma2ForImageClassification.forward™   sž   € ðR �$—*‘*ð 
ØØ%Ø)Ø%Ø+Ø)Ø)Ø'ØØØ/Ø!5Ø#Ø)ñ
ð ñ
ˆð" —‘ˆØ ¢ B¨×)=Ñ)=¸t×?RÑ?RÐ(SÐ!SÑTˆÜŸ™ o¸2Ô>ˆÜ?Ø"Ø'ô
ð 	
r   )NNNNNNNNNNNNNr   )r   r   r   r   Úconfig_classr&   r/   r2   r5   r7   r:   r=   r@   r   r   ÚSHIELDGEMMA2_INPUTS_DOCSTRINGr   r   Ú
LongTensorÚFloatTensorr   r   r   r   ÚboolÚintr   r[   Ú__classcell__)r+   s   @r   r    r    {   sº  ø„ Ø%€LðLÐ1õ Lò@ò>òAòHò7ò7ò7ñ Ð)°6ÐDTÔUÙ*Ð+HÓIð 15Ø48Ø15Ø37ØKOØ59Ø59Ø59Ø-1Ø$(Ø,0Ø/3Ø&*Ø34ñ>
à˜E×,Ñ,Ñ-ð>
ð ˜u×0Ñ0Ñ1ð>
ð ! §¡Ñ.ð	>
ð
 ˜u×/Ñ/Ñ0ð>
ð " %¨¨U×->Ñ->Ñ(?ÀÐ(FÑ"GÑHð>
ð ! ×!1Ñ!1Ñ2ð>
ð ! ×!1Ñ!1Ñ2ð>
ð   × 1Ñ 1Ñ2ð>
ð ˜×)Ñ)Ñ*ð>
ð ˜D‘>ð>
ð $ D™>ð>
ð ' t™nð>
ð ˜d‘^ð>
ð ˜c 5§<¡<Ð/Ñ0ð>
ð" 
:ò#>
ó Jó Vô>
r   r    ) Údataclassesr   Útypingr   r   r   r   Útorch.utils.checkpointÚcache_utilsr   Úmodeling_outputsr	   Úmodeling_utilsr
   Úutilsr   r   Úutils.deprecationr   Úautor   Úconfiguration_shieldgemma2r   Ú_CHECKPOINT_FOR_DOCÚ_CONFIG_FOR_DOCÚ
get_loggerr   Úloggerr]   r   r    Ú__all__r   r   r   ú<module>rr      s�   ðõ  "ß (Ñ (ã Û å  Ý DÝ -÷õ 1Ý .Ý :ð 3Ð Ø&€à	ˆ×	Ñ	˜HÓ	%€ðH!Ð ðV ô1Ð7[ó 1ó ð1ô^
¨ô ^
ðD )ð�r   