

import unittest

from transformers import FunnelConfig, FunnelTokenizer, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import (
           MODEL_FOR_PRETRAINING_MAPPING,
           FunnelBaseModel,
           FunnelForMaskedLM,
           FunnelForMultipleChoice,
           FunnelForPreTraining,
           FunnelForQuestionAnswering,
           FunnelForSequenceClassification,
           FunnelForTokenClassification,
           FunnelModel,
       )
class    A_				:


    '''simple docstring'''






    def __init__(self       , lowercase__       , lowercase__=13       , lowercase__=7       , lowercase__=True       , lowercase__=True       , lowercase__=True       , lowercase__=True       , lowercase__=99       , lowercase__=[1, 1, 2]       , lowercase__=1       , lowercase__=32       , lowercase__=4       , lowercase__=8       , lowercase__=37       , lowercase__="gelu_new"       , lowercase__=0.1       , lowercase__=0.1       , lowercase__=0.0       , lowercase__=512       , lowercase__=3       , lowercase__=0.02       , lowercase__=3       , lowercase__=4       , lowercase__=None       , lowercase__=False       , )       -> int:
        __UpperCAmelCase			   =     parent
        __UpperCAmelCase			   =     batch_size
        __UpperCAmelCase			   =     seq_length
        __UpperCAmelCase			   =     is_training
        __UpperCAmelCase			   =     use_input_mask
        __UpperCAmelCase			   =     use_token_type_ids
        __UpperCAmelCase			   =     use_labels
        __UpperCAmelCase			   =     vocab_size
        __UpperCAmelCase			   =     block_sizes
        __UpperCAmelCase			   =     num_decoder_layers
        __UpperCAmelCase			   =     d_model
        __UpperCAmelCase			   =     n_head
        __UpperCAmelCase			   =     d_head
        __UpperCAmelCase			   =     d_inner
        __UpperCAmelCase			   =     hidden_act
        __UpperCAmelCase			   =     hidden_dropout
        __UpperCAmelCase			   =     attention_dropout
        __UpperCAmelCase			   =     activation_dropout
        __UpperCAmelCase			   =     max_position_embeddings
        __UpperCAmelCase			   =     type_vocab_size
        __UpperCAmelCase			   =     2
        __UpperCAmelCase			   =     num_labels
        __UpperCAmelCase			   =     num_choices
        __UpperCAmelCase			   =     scope
        __UpperCAmelCase			   =     initializer_std

        # Used in the tests to check the size of the first attention layer
        __UpperCAmelCase			   =     n_head
        # Used in the tests to check the size of the first hidden state
        __UpperCAmelCase			   =     self.d_model
        # Used in the tests to check the number of output hidden states/attentions
        __UpperCAmelCase			   =     sum(self.block_sizes					) + (0 if base else self.num_decoder_layers)
        # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
        # the last hidden state of the first block (which is the first hidden state of the decoder).
        if not base:
            __UpperCAmelCase			   =     self.num_hidden_layers + 2


    def        lowerCAmelCase_  (self					)       -> Optional[int]:
        __UpperCAmelCase			   =     ids_tensor([self.batch_size, self.seq_length]       , self.vocab_size					)

        __UpperCAmelCase			   =     None
        if self.use_input_mask:
            __UpperCAmelCase			   =     ids_tensor([self.batch_size, self.seq_length]       , vocab_size=2					)

        __UpperCAmelCase			   =     None
        if self.use_token_type_ids:
            __UpperCAmelCase			   =     ids_tensor([self.batch_size, self.seq_length]       , self.type_vocab_size					)

        __UpperCAmelCase			   =     None
        __UpperCAmelCase			   =     None
        __UpperCAmelCase			   =     None
        if self.use_labels:
            __UpperCAmelCase			   =     ids_tensor([self.batch_size]       , self.type_sequence_label_size					)
            __UpperCAmelCase			   =     ids_tensor([self.batch_size, self.seq_length]       , self.num_labels					)
            __UpperCAmelCase			   =     ids_tensor([self.batch_size]       , self.num_choices					)
            __UpperCAmelCase			   =     ids_tensor([self.batch_size, self.seq_length]       , 1					)

        __UpperCAmelCase			   =     self.get_config()

        return (
            config,
            input_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
            fake_token_labels,
        )


    def        lowerCAmelCase_  (self					)       -> Optional[Any]:
        return FunnelConfig(
            vocab_size=self.vocab_size       , block_sizes=self.block_sizes       , num_decoder_layers=self.num_decoder_layers       , d_model=self.d_model       , n_head=self.n_head       , d_head=self.d_head       , d_inner=self.d_inner       , hidden_act=self.hidden_act       , hidden_dropout=self.hidden_dropout       , attention_dropout=self.attention_dropout       , activation_dropout=self.activation_dropout       , max_position_embeddings=self.max_position_embeddings       , type_vocab_size=self.type_vocab_size       , initializer_std=self.initializer_std       , )


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> Optional[Any]:
        __UpperCAmelCase			   =     FunnelModel(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__					)
        __UpperCAmelCase			   =     model(lowercase__       , token_type_ids=lowercase__					)
        __UpperCAmelCase			   =     model(lowercase__					)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, self.seq_length, self.d_model)					)

        __UpperCAmelCase			   =     False
        __UpperCAmelCase			   =     model(lowercase__					)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, self.seq_length, self.d_model)					)

        __UpperCAmelCase			   =     False
        __UpperCAmelCase			   =     model(lowercase__					)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, self.seq_length, self.d_model)					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> List[str]:
        __UpperCAmelCase			   =     FunnelBaseModel(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__					)
        __UpperCAmelCase			   =     model(lowercase__       , token_type_ids=lowercase__					)
        __UpperCAmelCase			   =     model(lowercase__					)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, 2, self.d_model)					)

        __UpperCAmelCase			   =     False
        __UpperCAmelCase			   =     model(lowercase__					)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, 3, self.d_model)					)

        __UpperCAmelCase			   =     False
        __UpperCAmelCase			   =     model(lowercase__					)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, 2, self.d_model)					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> List[Any]:
        __UpperCAmelCase			   =     self.num_labels
        __UpperCAmelCase			   =     FunnelForPreTraining(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__       , labels=lowercase__					)
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.seq_length)					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> Optional[Any]:
        __UpperCAmelCase			   =     FunnelForMaskedLM(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__       , labels=lowercase__					)
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.seq_length, self.vocab_size)					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> str:
        __UpperCAmelCase			   =     self.num_labels
        __UpperCAmelCase			   =     FunnelForSequenceClassification(lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__       , labels=lowercase__					)
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.num_labels)					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> Optional[Any]:
        __UpperCAmelCase			   =     self.num_choices
        __UpperCAmelCase			   =     FunnelForMultipleChoice(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     input_ids.unsqueeze(1					).expand(-1       , self.num_choices       , -1					).contiguous()
        __UpperCAmelCase			   =     token_type_ids.unsqueeze(1					).expand(-1       , self.num_choices       , -1					).contiguous()
        __UpperCAmelCase			   =     input_mask.unsqueeze(1					).expand(-1       , self.num_choices       , -1					).contiguous()
        __UpperCAmelCase			   =     model(
            lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__       , labels=lowercase__       , )
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.num_choices)					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> Tuple:
        __UpperCAmelCase			   =     self.num_labels
        __UpperCAmelCase			   =     FunnelForTokenClassification(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__       , labels=lowercase__					)
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.seq_length, self.num_labels)					)


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , lowercase__       , )       -> List[Any]:
        __UpperCAmelCase			   =     FunnelForQuestionAnswering(config=lowercase__					)
        model.to(lowercase__					)
        model.eval()
        __UpperCAmelCase			   =     model(
            lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__       , start_positions=lowercase__       , end_positions=lowercase__       , )
        self.parent.assertEqual(result.start_logits.shape       , (self.batch_size, self.seq_length)					)
        self.parent.assertEqual(result.end_logits.shape       , (self.batch_size, self.seq_length)					)






    def        lowerCAmelCase_  (self					)       -> Optional[int]:
        __UpperCAmelCase			   =     self.prepare_config_and_inputs()
        (
            (
            __UpperCAmelCase
        )   ,       (
            __UpperCAmelCase
        )   ,       (
            __UpperCAmelCase
        )   ,       (
            __UpperCAmelCase
        )   ,       (
            __UpperCAmelCase
        )   ,       (
            __UpperCAmelCase
        )   ,       (
            __UpperCAmelCase
        )   ,       (
            __UpperCAmelCase
        )   ,       
        )			   =     config_and_inputs
        __UpperCAmelCase			   =     {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
        return config, inputs_dict






@require_torch
class    A_				( _a	,       _a	,       unittest.TestCase  ):


    '''simple docstring'''






    a__       							=    False
    a__       							=    False
    a__       							=    (
        (
            FunnelModel,
            FunnelForMaskedLM,
            FunnelForPreTraining,
            FunnelForQuestionAnswering,
            FunnelForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    a__       							=    (
        {
            "feature-extraction": (FunnelBaseModel, FunnelModel),
            "fill-mask": FunnelForMaskedLM,
            "question-answering": FunnelForQuestionAnswering,
            "text-classification": FunnelForSequenceClassification,
            "token-classification": FunnelForTokenClassification,
            "zero-shot": FunnelForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )


    def        lowerCAmelCase_  (self       , lowercase__       , lowercase__       , lowercase__=False					)       -> Optional[Any]:
        __UpperCAmelCase			   =     super()._prepare_for_class(lowercase__       , lowercase__       , return_labels=lowercase__					)

        if return_labels:
            if model_class in get_values(lowercase__					):
                __UpperCAmelCase			   =     torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length)       , dtype=torch.long       , device=lowercase__					)
        return inputs_dict


    def        lowerCAmelCase_  (self					)       -> Dict:
        __UpperCAmelCase			   =     FunnelModelTester(self					)
        __UpperCAmelCase			   =     ConfigTester(self       , config_class=lowercase__					)


    def        lowerCAmelCase_  (self					)       -> str:
        self.config_tester.run_common_tests()


    def        lowerCAmelCase_  (self					)       -> Optional[Any]:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> List[Any]:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_pretraining(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> Optional[Any]:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> Optional[int]:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> Any:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*lowercase__					)






    def        lowerCAmelCase_  (self       , lowercase__					)       -> Optional[int]:
        if hasattr(lowercase__       , '''weight'''					) and module.weight is not None:
            module.weight.data.fill_(3					)
        if hasattr(lowercase__       , '''bias'''					) and module.bias is not None:
            module.bias.data.fill_(3					)

        for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
            if hasattr(lowercase__       , lowercase__					) and getattr(lowercase__       , lowercase__					) is not None:
                __UpperCAmelCase			   =     getattr(lowercase__       , lowercase__					)
                weight.data.fill_(3					)






@require_torch
class    A_				( _a	,       unittest.TestCase  ):


    '''simple docstring'''






    a__       							=    False
    a__       							=    False
    a__       							=    (
        (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
    )


    def        lowerCAmelCase_  (self					)       -> Tuple:
        __UpperCAmelCase			   =     FunnelModelTester(self       , base=lowercase__					)
        __UpperCAmelCase			   =     ConfigTester(self       , config_class=lowercase__					)


    def        lowerCAmelCase_  (self					)       -> Tuple:
        self.config_tester.run_common_tests()


    def        lowerCAmelCase_  (self					)       -> Any:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_base_model(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> str:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> List[Any]:
        __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*lowercase__					)


    def        lowerCAmelCase_  (self					)       -> List[Any]:
        __UpperCAmelCase   ,       __UpperCAmelCase			   =     self.model_tester.prepare_config_and_inputs_for_common()
        __UpperCAmelCase			   =     True

        for model_class in self.all_model_classes:
            if model_class.__name__ == "FunnelBaseModel":
                continue
            __UpperCAmelCase			   =     model_class(lowercase__					)
            model.to(lowercase__					)
            model.train()
            __UpperCAmelCase			   =     self._prepare_for_class(lowercase__       , lowercase__       , return_labels=lowercase__					)
            __UpperCAmelCase			   =     model(**lowercase__					).loss
            loss.backward()






    def        lowerCAmelCase_  (self       , lowercase__					)       -> List[Any]:
        if hasattr(lowercase__       , '''weight'''					) and module.weight is not None:
            module.weight.data.fill_(3					)
        if hasattr(lowercase__       , '''bias'''					) and module.bias is not None:
            module.bias.data.fill_(3					)

        for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
            if hasattr(lowercase__       , lowercase__					) and getattr(lowercase__       , lowercase__					) is not None:
                __UpperCAmelCase			   =     getattr(lowercase__       , lowercase__					)
                weight.data.fill_(3					)






@require_torch
@require_sentencepiece
@require_tokenizers
class    A_				( unittest.TestCase  ):


    '''simple docstring'''






    def        lowerCAmelCase_  (self					)       -> int:
        __UpperCAmelCase			   =     13
        __UpperCAmelCase			   =     7
        __UpperCAmelCase			   =     torch.arange(0       , batch_size * sequence_length					).long().reshape(lowercase__       , lowercase__					)
        __UpperCAmelCase			   =     [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
        __UpperCAmelCase			   =     torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths]					)

        __UpperCAmelCase			   =     FunnelModel.from_pretrained('''sgugger/funnel-random-tiny'''					)
        __UpperCAmelCase			   =     model(lowercase__       , token_type_ids=lowercase__					)[0].abs()

        __UpperCAmelCase			   =     torch.tensor(2344.8352					)
        __UpperCAmelCase			   =     torch.tensor(0.8052					)
        self.assertTrue(torch.allclose(output.sum()       , lowercase__       , atol=1E-4					)					)
        self.assertTrue(torch.allclose(output.mean()       , lowercase__       , atol=1E-4					)					)

        __UpperCAmelCase			   =     torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]]					)
        __UpperCAmelCase			   =     model(lowercase__       , attention_mask=lowercase__       , token_type_ids=lowercase__					)[0].abs()

        __UpperCAmelCase			   =     torch.tensor(2343.8425					)
        __UpperCAmelCase			   =     torch.tensor(0.8049					)
        self.assertTrue(torch.allclose(output.sum()       , lowercase__       , atol=1E-4					)					)
        self.assertTrue(torch.allclose(output.mean()       , lowercase__       , atol=1E-4					)					)






    @slow
    def        lowerCAmelCase_  (self					)       -> Union[str, Any]:
        __UpperCAmelCase			   =     FunnelTokenizer.from_pretrained('''huggingface/funnel-small'''					)
        __UpperCAmelCase			   =     FunnelModel.from_pretrained('''huggingface/funnel-small'''					)
        __UpperCAmelCase			   =     tokenizer('''Hello! I am the Funnel Transformer model.'''       , return_tensors='''pt'''					)
        __UpperCAmelCase			   =     model(**lowercase__					)[0]

        __UpperCAmelCase			   =     torch.tensor(235.7246					)
        __UpperCAmelCase			   =     torch.tensor(0.0256					)
        self.assertTrue(torch.allclose(output.sum()       , lowercase__       , atol=1E-4					)					)
        self.assertTrue(torch.allclose(output.mean()       , lowercase__       , atol=1E-4					)					)







import warnings

from ...utils import logging
from .image_processing_convnext import ConvNextImageProcessor


A_						:     int			  =				logging.get_logger(__name__)
class    A_				( _a  ):


    '''simple docstring'''






    def __init__(self       , *lowercase__       , **lowercase__					)       -> None:
        warnings.warn(
            '''The class ConvNextFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
            ''' Please use ConvNextImageProcessor instead.'''       , lowercase__       , )
        super().__init__(*lowercase__       , **lowercase__					)




