"""simple docstring"""


import logging
import os
from dataclasses import dataclass, field
from importlib import import_module
from typing import Dict, List, Optional, Tuple

import numpy as np
from seqeval.metrics import classification_report, fa_score, precision_score, recall_score
from utils_ner import Split, TFTokenClassificationDataset, TokenClassificationTask

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    TFAutoModelForTokenClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()


__UpperCamelCase										=     logging.getLogger(__name__)




@dataclass
class 					UpperCamelCase   :
       SCREAMING_SNAKE_CASE_						      = field(
           metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}  )
       SCREAMING_SNAKE_CASE_						      = field(
           default=lowerCAmelCase__       ,						metadata={"help": "Pretrained config name or path if not the same as model_name"}  )
       SCREAMING_SNAKE_CASE_						      = field(
           default="NER"       ,						metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"}  )
       SCREAMING_SNAKE_CASE_						      = field(
           default=lowerCAmelCase__       ,						metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}  )
       SCREAMING_SNAKE_CASE_						      = field(default=lowerCAmelCase__       ,						metadata={"help": "Set this flag to use fast tokenization."}  )
       # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
       # or just modify its tokenizer_config.json.
       SCREAMING_SNAKE_CASE_						      = field(
           default=lowerCAmelCase__       ,						metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}       ,						)




@dataclass
class 					UpperCamelCase   :
       SCREAMING_SNAKE_CASE_						      = field(
           metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."}  )
       SCREAMING_SNAKE_CASE_						      = field(
           metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."}  )
       SCREAMING_SNAKE_CASE_						      = field(
           default=1_2_8       ,						metadata={
               "help": (
                   "The maximum total input sequence length after tokenization. Sequences longer "
                   "than this will be truncated, sequences shorter will be padded."
               )
           }       ,						)
       SCREAMING_SNAKE_CASE_						      = field(
           default=lowerCAmelCase__       ,						metadata={"help": "Overwrite the cached training and evaluation sets"}  )







def    UpperCAmelCase       (						)							-> Union[str, Any]:
     # See all possible arguments in src/transformers/training_args.py
     # or by passing the --help flag to this script.
     # We now keep distinct sets of args, for a cleaner separation of concerns.
     snake_case_   			=   HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)   )
     snake_case_			,      snake_case_			,      snake_case_   			=   parser.parse_args_into_dataclasses()

     if (
         os.path.exists(training_args.output_dir   )
         and os.listdir(training_args.output_dir   )
         and training_args.do_train
         and not training_args.overwrite_output_dir
     ):
          raise ValueError(
              f'Output directory ({training_args.output_dir}) already exists and is not empty. Use'
              ' --overwrite_output_dir to overcome.'   )

     snake_case_   			=   import_module('tasks'   )

     try:
          snake_case_   			=   getattr(UpperCAmelCase		,   model_args.task_type   )
          snake_case_   			=   token_classification_task_clazz()
     except AttributeError:
          raise ValueError(
              f'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. '
              f'Available tasks classes are: {TokenClassificationTask.__subclasses__()}'   )

     # Setup logging
     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'		,   datefmt='%m/%d/%Y %H:%M:%S'		,   level=logging.INFO		,   )
     logger.info(
         'n_replicas: %s, distributed training: %s, 16-bits training: %s'		,   training_args.n_replicas		,   bool(training_args.n_replicas > 1   )		,   training_args.fpaa		,   )
     logger.info('Training/evaluation parameters %s'		,   UpperCAmelCase   )

     # Prepare Token Classification task
     snake_case_   			=   token_classification_task.get_labels(data_args.labels   )
     snake_case_   			=   dict(enumerate(UpperCAmelCase   )   )
     snake_case_   			=   len(UpperCAmelCase   )

     # Load pretrained model and tokenizer
     #
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.

     snake_case_   			=   AutoConfig.from_pretrained(
         model_args.config_name if model_args.config_name else model_args.model_name_or_path		,   num_labels=UpperCAmelCase		,   idalabel=UpperCAmelCase		,   labelaid={label: i for i, label in enumerate(UpperCAmelCase   )}		,   cache_dir=model_args.cache_dir		,   )
     snake_case_   			=   AutoTokenizer.from_pretrained(
         model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path		,   cache_dir=model_args.cache_dir		,   use_fast=model_args.use_fast		,   )

     with training_args.strategy.scope():
          snake_case_   			=   TFAutoModelForTokenClassification.from_pretrained(
              model_args.model_name_or_path		,   from_pt=bool('.bin' in model_args.model_name_or_path   )		,   config=UpperCAmelCase		,   cache_dir=model_args.cache_dir		,   )

     # Get datasets
     snake_case_   			=   (
         TFTokenClassificationDataset(
             token_classification_task=UpperCAmelCase		,   data_dir=data_args.data_dir		,   tokenizer=UpperCAmelCase		,   labels=UpperCAmelCase		,   model_type=config.model_type		,   max_seq_length=data_args.max_seq_length		,   overwrite_cache=data_args.overwrite_cache		,   mode=Split.train		,   )
         if training_args.do_train
         else None
     )
     snake_case_   			=   (
         TFTokenClassificationDataset(
             token_classification_task=UpperCAmelCase		,   data_dir=data_args.data_dir		,   tokenizer=UpperCAmelCase		,   labels=UpperCAmelCase		,   model_type=config.model_type		,   max_seq_length=data_args.max_seq_length		,   overwrite_cache=data_args.overwrite_cache		,   mode=Split.dev		,   )
         if training_args.do_eval
         else None
     )

     def align_predictions(UpperCAmelCase		,   UpperCAmelCase   ) -> Tuple[List[int], List[int]]:
          snake_case_   			=   np.argmax(UpperCAmelCase		,   axis=2   )
          snake_case_			,      snake_case_   			=   preds.shape
          snake_case_   			=   [[] for _ in range(UpperCAmelCase   )]
          snake_case_   			=   [[] for _ in range(UpperCAmelCase   )]

          for i in range(UpperCAmelCase   ):
               for j in range(UpperCAmelCase   ):
                    if label_ids[i, j] != -100:
                         out_label_list[i].append(label_map[label_ids[i][j]]   )
                         preds_list[i].append(label_map[preds[i][j]]   )

          return preds_list, out_label_list

     def compute_metrics(UpperCAmelCase   ) -> Dict:
          snake_case_			,      snake_case_   			=   align_predictions(p.predictions		,   p.label_ids   )

          return {
              "precision": precision_score(UpperCAmelCase		,   UpperCAmelCase   ),
              "recall": recall_score(UpperCAmelCase		,   UpperCAmelCase   ),
              "f1": fa_score(UpperCAmelCase		,   UpperCAmelCase   ),
          }

     # Initialize our Trainer
     snake_case_   			=   TFTrainer(
         model=UpperCAmelCase		,   args=UpperCAmelCase		,   train_dataset=train_dataset.get_dataset() if train_dataset else None		,   eval_dataset=eval_dataset.get_dataset() if eval_dataset else None		,   compute_metrics=UpperCAmelCase		,   )

     # Training
     if training_args.do_train:
          trainer.train()
          trainer.save_model()
          tokenizer.save_pretrained(training_args.output_dir   )

     # Evaluation
     snake_case_   			=   {}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'   )

          snake_case_   			=   trainer.evaluate()
          snake_case_   			=   os.path.join(training_args.output_dir		,   'eval_results.txt'   )

          with open(UpperCAmelCase		,   'w'   ) as writer:
               logger.info('***** Eval results *****'   )

               for key, value in result.items():
                    logger.info('  %s = %s'		,   UpperCAmelCase		,   UpperCAmelCase   )
                    writer.write('%s = %s\n' % (key, value)   )

               results.update(UpperCAmelCase   )

    # Predict
     if training_args.do_predict:
          snake_case_   			=   TFTokenClassificationDataset(
              token_classification_task=UpperCAmelCase		,   data_dir=data_args.data_dir		,   tokenizer=UpperCAmelCase		,   labels=UpperCAmelCase		,   model_type=config.model_type		,   max_seq_length=data_args.max_seq_length		,   overwrite_cache=data_args.overwrite_cache		,   mode=Split.test		,   )

          snake_case_			,      snake_case_			,      snake_case_   			=   trainer.predict(test_dataset.get_dataset()   )
          snake_case_			,      snake_case_   			=   align_predictions(UpperCAmelCase		,   UpperCAmelCase   )
          snake_case_   			=   classification_report(UpperCAmelCase		,   UpperCAmelCase   )

          logger.info('\n%s'		,   UpperCAmelCase   )

          snake_case_   			=   os.path.join(training_args.output_dir		,   'test_results.txt'   )

          with open(UpperCAmelCase		,   'w'   ) as writer:
               writer.write('%s\n' % report   )

          # Save predictions
          snake_case_   			=   os.path.join(training_args.output_dir		,   'test_predictions.txt'   )

          with open(UpperCAmelCase		,   'w'   ) as writer:
               with open(os.path.join(data_args.data_dir		,   'test.txt'   )		,   'r'   ) as f:
                    snake_case_   			=   0

                    for line in f:
                         if line.startswith('-DOCSTART-'   ) or line == "" or line == "\n":
                              writer.write(UpperCAmelCase   )

                              if not preds_list[example_id]:
                                   example_id += 1
                         elif preds_list[example_id]:
                              snake_case_   			=   line.split()[0] + ' ' + preds_list[example_id].pop(0   ) + '\n'

                              writer.write(UpperCAmelCase   )
                         else:
                              logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.'		,   line.split()[0]   )

     return results


if __name__ == "__main__":
    main()


"""simple docstring"""


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 					UpperCamelCase   :







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

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







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

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

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

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

            snake_case_   			=   self.get_config()

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







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

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

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







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

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

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







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







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







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__,				) -> Optional[int]:
            snake_case_   			=   self.num_labels
            snake_case_   			=   FunnelForSequenceClassification(lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_   			=   model(lowerCAmelCase__,				attention_mask=lowerCAmelCase__,				token_type_ids=lowerCAmelCase__,				labels=lowerCAmelCase__)
            self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.num_labels))







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







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







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




@require_torch
class 					UpperCamelCase   (							lowerCAmelCase__       ,						lowerCAmelCase__       ,						unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = (
           (
               FunnelModel,
               FunnelForMaskedLM,
               FunnelForPreTraining,
               FunnelForQuestionAnswering,
               FunnelForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       SCREAMING_SNAKE_CASE_						      = (
           {
               "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 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__=False) -> List[Any]:
            snake_case_   			=   super()._prepare_for_class(lowerCAmelCase__,				lowerCAmelCase__,				return_labels=lowerCAmelCase__)

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







       def 						a_		(					self) -> List[Any]:
            snake_case_   			=   FunnelModelTester(self)
            snake_case_   			=   ConfigTester(self,				config_class=lowerCAmelCase__)







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







       def 						a_		(					self) -> Dict:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowerCAmelCase__)







       def 						a_		(					self) -> Optional[Any]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__)







       def 						a_		(					self) -> List[str]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__)







       def 						a_		(					self) -> int:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__)







       def 						a_		(					self) -> Any:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__)







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




@require_torch
class 					UpperCamelCase   (							lowerCAmelCase__       ,						unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = False
       SCREAMING_SNAKE_CASE_						      = (
           (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
       )







       def 						a_		(					self) -> List[Any]:
            snake_case_   			=   FunnelModelTester(self,				base=lowerCAmelCase__)
            snake_case_   			=   ConfigTester(self,				config_class=lowerCAmelCase__)







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







       def 						a_		(					self) -> str:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_base_model(*lowerCAmelCase__)







       def 						a_		(					self) -> Optional[Any]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__)







       def 						a_		(					self) -> List[Any]:
            snake_case_   			=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__)







       def 						a_		(					self) -> Union[str, Any]:
            snake_case_			,      snake_case_   			=   self.model_tester.prepare_config_and_inputs_for_common()
            snake_case_   			=   True

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







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




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







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

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

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

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

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







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

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

