





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     lowerCamelCase:
     '''simple docstring'''


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

         # Used in the tests to check the size of the first attention layer
         _A    =       n_head
         # Used in the tests to check the size of the first hidden state
         _A    =       self.d_model
         # Used in the tests to check the number of output hidden states/attentions
         _A    =       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:
             _A    =       self.num_hidden_layers + 2




     def 					lowerCAmelCase__		(						self       ):
         _A    =       ids_tensor([self.batch_size, self.seq_length]							,    self.vocab_size       )

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

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

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

         _A    =       self.get_config()

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




     def 					lowerCAmelCase__		(						self       ):
         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							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       FunnelModel(config=snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       model(snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_       )
         _A    =       model(snake_case_							,    token_type_ids=snake_case_       )
         _A    =       model(snake_case_       )
         self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.d_model)       )

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

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




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       FunnelBaseModel(config=snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       model(snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_       )
         _A    =       model(snake_case_							,    token_type_ids=snake_case_       )
         _A    =       model(snake_case_       )
         self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, 2, self.d_model)       )

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

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




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       self.num_labels
         _A    =       FunnelForPreTraining(config=snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       model(snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_							,    labels=snake_case_       )
         self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length)       )




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       FunnelForMaskedLM(config=snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       model(snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_							,    labels=snake_case_       )
         self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.vocab_size)       )




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       self.num_labels
         _A    =       FunnelForSequenceClassification(snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       model(snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_							,    labels=snake_case_       )
         self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)       )




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       self.num_choices
         _A    =       FunnelForMultipleChoice(config=snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       input_ids.unsqueeze(1       ).expand(-1							,    self.num_choices							,    -1       ).contiguous()
         _A    =       token_type_ids.unsqueeze(1       ).expand(-1							,    self.num_choices							,    -1       ).contiguous()
         _A    =       input_mask.unsqueeze(1       ).expand(-1							,    self.num_choices							,    -1       ).contiguous()
         _A    =       model(
             snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_							,    labels=snake_case_							,    )
         self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_choices)       )




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       self.num_labels
         _A    =       FunnelForTokenClassification(config=snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       model(snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_							,    labels=snake_case_       )
         self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.num_labels)       )




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         _A    =       FunnelForQuestionAnswering(config=snake_case_       )
         model.to(snake_case_       )
         model.eval()
         _A    =       model(
             snake_case_							,    attention_mask=snake_case_							,    token_type_ids=snake_case_							,    start_positions=snake_case_							,    end_positions=snake_case_							,    )
         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       ):
         _A    =       self.prepare_config_and_inputs()
         (
             (
             _A
         ), (
             _A
         ), (
             _A
         ), (
             _A
         ), (
             _A
         ), (
             _A
         ), (
             _A
         ), (
             _A
         ), 
         )    =       config_and_inputs
         _A    =       {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
         return config, inputs_dict







@require_torch
class     lowerCamelCase(	__snake_case ,   __snake_case ,   unittest.TestCase  ):
     '''simple docstring'''


     __magic_name__        = False
     __magic_name__        = False
     __magic_name__        = (
         (
             FunnelModel,
             FunnelForMaskedLM,
             FunnelForPreTraining,
             FunnelForQuestionAnswering,
             FunnelForTokenClassification,
         )
         if is_torch_available()
         else ()
     )
     __magic_name__        = (
         {
             '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							,    snake_case_							,    snake_case_							,    snake_case_=False       ):
         _A    =       super()._prepare_for_class(snake_case_							,    snake_case_							,    return_labels=snake_case_       )

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




     def 					lowerCAmelCase__		(						self       ):
         _A    =       FunnelModelTester(self       )
         _A    =       ConfigTester(self							,    config_class=snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         self.config_tester.run_common_tests()




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_pretraining(*snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*snake_case_       )




     def 					lowerCAmelCase__		(						self							,    snake_case_       ):
         if hasattr(snake_case_							,    'weight'       ) and module.weight is not None:
             module.weight.data.fill_(3       )
         if hasattr(snake_case_							,    '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(snake_case_							,    snake_case_       ) and getattr(snake_case_							,    snake_case_       ) is not None:
                 _A    =       getattr(snake_case_							,    snake_case_       )
                 weight.data.fill_(3       )







@require_torch
class     lowerCamelCase(	__snake_case ,   unittest.TestCase  ):
     '''simple docstring'''


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




     def 					lowerCAmelCase__		(						self       ):
         _A    =       FunnelModelTester(self							,    base=snake_case_       )
         _A    =       ConfigTester(self							,    config_class=snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         self.config_tester.run_common_tests()




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_base_model(*snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(*snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         _A    =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_multiple_choice(*snake_case_       )




     def 					lowerCAmelCase__		(						self       ):
         _A, _A    =       self.model_tester.prepare_config_and_inputs_for_common()
         _A    =       True

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




     def 					lowerCAmelCase__		(						self							,    snake_case_       ):
         if hasattr(snake_case_							,    'weight'       ) and module.weight is not None:
             module.weight.data.fill_(3       )
         if hasattr(snake_case_							,    '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(snake_case_							,    snake_case_       ) and getattr(snake_case_							,    snake_case_       ) is not None:
                 _A    =       getattr(snake_case_							,    snake_case_       )
                 weight.data.fill_(3       )







@require_torch
@require_sentencepiece
@require_tokenizers
class     lowerCamelCase(	unittest.TestCase  ):
     '''simple docstring'''


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

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

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

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

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




     @slow
     def 					lowerCAmelCase__		(						self       ):
         _A    =       FunnelTokenizer.from_pretrained('huggingface/funnel-small'       )
         _A    =       FunnelModel.from_pretrained('huggingface/funnel-small'       )
         _A    =       tokenizer('Hello! I am the Funnel Transformer model.'							,    return_tensors='pt'       )
         _A    =       model(**snake_case_       )[0]

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












from transformers import SqueezeBertTokenizer, SqueezeBertTokenizerFast
from transformers.testing_utils import require_tokenizers, slow

from ..bert.test_tokenization_bert import BertTokenizationTest







@require_tokenizers
class     lowerCamelCase(	__snake_case  ):
     '''simple docstring'''


     __magic_name__        = SqueezeBertTokenizer
     __magic_name__        = SqueezeBertTokenizerFast
     __magic_name__        = True




     def 					lowerCAmelCase__		(						self							,    **snake_case_       ):
         return SqueezeBertTokenizerFast.from_pretrained(self.tmpdirname							,    **snake_case_       )




     @slow
     def 					lowerCAmelCase__		(						self       ):
         _A    =       SqueezeBertTokenizer.from_pretrained('squeezebert/squeezebert-mnli-headless'       )

         _A    =       tokenizer.encode('sequence builders'							,    add_special_tokens=snake_case_       )
         _A    =       tokenizer.encode('multi-sequence build'							,    add_special_tokens=snake_case_       )

         _A    =       tokenizer.build_inputs_with_special_tokens(snake_case_       )
         _A    =       tokenizer.build_inputs_with_special_tokens(snake_case_							,    snake_case_       )

         assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
         assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
             tokenizer.sep_token_id
         ]





