






import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
		import torch


__magic_name__:  Any  	=			logging.get_logger(__name__)





class  snake_case__      :
	def __init__(       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__=21    ,     lowerCAmelCase__=[]    ,     lowerCAmelCase__=None				)							->   List[Any]:
							__magic_name__    :     Any     		=      model
							__magic_name__    :     int     		=      trace_batch_nums
							__magic_name__    :     Tuple     		=      abort_after_batch_num

							# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
							__magic_name__    :     str     		=      collections.deque([]    ,     lowerCAmelCase__				)
							__magic_name__    :     Optional[int]     		=      []
							__magic_name__    :     int     		=      0
							__magic_name__    :     Dict     		=      0
							__magic_name__    :     Union[str, Any]     		=      False
							__magic_name__    :     Union[str, Any]     		=      """                 """

							self.analyse_model()

							self.register_forward_hook()
	def     __magic_name__       (       self    ,     lowerCAmelCase__=None				)							->   Union[str, Any]:
							if frame is not None:
													self.expand_frame(lowerCAmelCase__				)
							self.frames.append("""\n""".join(self.frame				)				)
							__magic_name__    :     Optional[Any]     		=      []  # start a new frame
	def     __magic_name__       (       self    ,     lowerCAmelCase__				)							->   int:
							self.frame.append(lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   List[Any]:
							print("""\n""".join(self.frames				)				)
							__magic_name__    :     Any     		=      []
	def     __magic_name__       (       self				)							->   Any:
							__magic_name__    :     Union[str, Any]     		=      []
	def     __magic_name__       (       self				)							->   Any:
							print(F'\nDetected inf/nan during batch_number={self.batch_number}'				)
							print(F'Last {len(self.frames				)} forward frames:'				)
							print(F'{"abs min":8} {"abs max":8} metadata'				)
							print("""\n""".join(self.frames				)				)
							print("""\n\n"""				)
							__magic_name__    :     Union[str, Any]     		=      []
	def     __magic_name__       (       self				)							->   int:
							# extract the fully qualified module names, to be able to report at run time. e.g.:
							# encoder.block.2.layer.0.SelfAttention.o
							#
							# for shared weights only the first shared module name will be registered
							__magic_name__    :     str     		=      {m: name for name, m in self.model.named_modules()}
							# self.longest_module_name = max(len(v) for v in self.module_names.values())
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)							->   Tuple:
							if torch.is_tensor(lowerCAmelCase__				):
													self.expand_frame(get_abs_min_max(lowerCAmelCase__    ,     lowerCAmelCase__				)				)
													if detect_overflow(lowerCAmelCase__    ,     lowerCAmelCase__				):
																			__magic_name__    :     Optional[int]     		=      True
							elif var is None:
													self.expand_frame(F'{"None":>17} {ctx}'				)
							else:
													self.expand_frame(F'{"not a tensor":>17} {ctx}'				)
	def     __magic_name__       (       self				)							->   Any:
							self.expand_frame(F'\n\n{self.prefix} *** Starting batch number={self.batch_number} ***'				)
							self.expand_frame(F'{"abs min":8} {"abs max":8} metadata'				)
	def     __magic_name__       (       self				)							->   List[Any]:
							self.expand_frame(F'{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)							->   str:
							self.expand_frame(F'{self.prefix} {self.module_names[module]} {module.__class__.__name__}'				)

							# params
							for name, p in module.named_parameters(recurse=lowerCAmelCase__				):
													self.analyse_variable(lowerCAmelCase__    ,     lowerCAmelCase__				)

							# inputs
							if isinstance(lowerCAmelCase__    ,     lowerCAmelCase__				):
													for i, x in enumerate(lowerCAmelCase__				):
																			self.analyse_variable(lowerCAmelCase__    ,     F'input[{i}]'				)
							else:
													self.analyse_variable(lowerCAmelCase__    ,     """input"""				)

							# outputs
							if isinstance(lowerCAmelCase__    ,     lowerCAmelCase__				):
													for i, x in enumerate(lowerCAmelCase__				):
																			# possibly a tuple of tuples
																			if isinstance(lowerCAmelCase__    ,     lowerCAmelCase__				):
																									for j, y in enumerate(lowerCAmelCase__				):
																															self.analyse_variable(lowerCAmelCase__    ,     F'output[{i}][{j}]'				)
																			else:
																									self.analyse_variable(lowerCAmelCase__    ,     F'output[{i}]'				)
							else:
													self.analyse_variable(lowerCAmelCase__    ,     """output"""				)

							self.save_frame()
	def     __magic_name__       (       self				)							->   Any:
							self.model.apply(self._register_forward_hook				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__				)							->   List[str]:
							module.register_forward_hook(self.forward_hook				)







	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)							->   Dict:
							# - input is a tuple of packed inputs (could be non-Tensors)
							# - output could be a Tensor or a tuple of Tensors and non-Tensors

							__magic_name__    :     Dict     		=      False

							__magic_name__    :     Tuple     		=      True if self.batch_number in self.trace_batch_nums else False
							if trace_mode:
													self.reset_saved_frames()

							if self.total_calls == 0:
													self.batch_start_frame()
							self.total_calls += 1

							# count batch numbers - the very first forward hook of the batch will be called when the
							# batch completes - i.e. it gets called very last - we know this batch has finished
							if module == self.model:
													self.batch_number += 1
													__magic_name__    :     List[Any]     		=      True

							self.create_frame(lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)

							# if last_frame_of_batch:
							#     self.batch_end_frame()

							if trace_mode:
													self.trace_frames()

							if last_frame_of_batch:
													self.batch_start_frame()

							if self.detected_overflow and not trace_mode:
													self.dump_saved_frames()

													# now we can abort, as it's pointless to continue running
													raise ValueError(
													    """DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. """
													    """Please scroll up above this traceback to see the activation values prior to this event."""				)

							# abort after certain batch if requested to do so
							if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
													raise ValueError(
													    F'DebugUnderflowOverflow: aborting after {self.batch_number} batches due to'
													    F' `abort_after_batch_num={self.abort_after_batch_num}` arg'				)



def 					UpperCamelCase		( _A,					_A				):






						"""simple docstring"""







						__magic_name__    :     Any     		=      var.abs()
						return f'{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'

def 					UpperCamelCase		( _A,					_A				):






						"""simple docstring"""







						__magic_name__    :     Union[str, Any]     		=      False
						if torch.isnan(_A				).any().item():
												__magic_name__    :     str     		=      True
												print(f'{ctx} has nans'				)
						if torch.isinf(_A				).any().item():
												__magic_name__    :     Optional[int]     		=      True
												print(f'{ctx} has infs'				)

						# if needed to monitor large elements can enable the following
						if 0:  # and detected:
												__magic_name__    :     str     		=      var[torch.ge(var.abs(),					100				)]
												if naaa.numel() > 0:
																		print(f'{ctx}:  n100={naaa.numel()}'				)
												__magic_name__    :     Optional[int]     		=      var[torch.ge(var.abs(),					1000				)]
												if naaaa.numel() > 0:
																		print(f'{ctx}: n1000={naaaa.numel()}'				)
												__magic_name__    :     Dict     		=      var[torch.ge(var.abs(),					10000				)]
												if naaaaa.numel() > 0:
																		print(f'{ctx}: n10000={naaaaa.numel()}'				)

						if 0:
												print(f'min={var.min():9.2e} max={var.max():9.2e}'				)

						if 0:
												print(f'min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})'				)

						return detected





class  snake_case__      (							_lowerCAmelCase   ):
	lowercase__		:  Tuple							   =					'''underflow_overflow'''
	lowercase__		:  Optional[int]							   =					'''tpu_metrics_debug'''








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  snake_case__      :
	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__=5_12    ,     lowerCAmelCase__=3    ,     lowerCAmelCase__=0.0_2    ,     lowerCAmelCase__=3    ,     lowerCAmelCase__=4    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=False    ,     )							->   Union[str, Any]:
							__magic_name__    :     Dict     		=      parent
							__magic_name__    :     List[str]     		=      batch_size
							__magic_name__    :     Dict     		=      seq_length
							__magic_name__    :     Optional[Any]     		=      is_training
							__magic_name__    :     Any     		=      use_input_mask
							__magic_name__    :     Dict     		=      use_token_type_ids
							__magic_name__    :     Tuple     		=      use_labels
							__magic_name__    :     Dict     		=      vocab_size
							__magic_name__    :     Dict     		=      block_sizes
							__magic_name__    :     Union[str, Any]     		=      num_decoder_layers
							__magic_name__    :     Dict     		=      d_model
							__magic_name__    :     List[Any]     		=      n_head
							__magic_name__    :     Any     		=      d_head
							__magic_name__    :     int     		=      d_inner
							__magic_name__    :     Optional[Any]     		=      hidden_act
							__magic_name__    :     Optional[int]     		=      hidden_dropout
							__magic_name__    :     Dict     		=      attention_dropout
							__magic_name__    :     Optional[Any]     		=      activation_dropout
							__magic_name__    :     List[Any]     		=      max_position_embeddings
							__magic_name__    :     int     		=      type_vocab_size
							__magic_name__    :     Union[str, Any]     		=      2
							__magic_name__    :     Dict     		=      num_labels
							__magic_name__    :     Dict     		=      num_choices
							__magic_name__    :     Tuple     		=      scope
							__magic_name__    :     Union[str, Any]     		=      initializer_std

							# Used in the tests to check the size of the first attention layer
							__magic_name__    :     List[Any]     		=      n_head
							# Used in the tests to check the size of the first hidden state
							__magic_name__    :     int     		=      self.d_model
							# Used in the tests to check the number of output hidden states/attentions
							__magic_name__    :     Tuple     		=      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:
													__magic_name__    :     Optional[int]     		=      self.num_hidden_layers + 2
	def     __magic_name__       (       self				)							->   Union[str, Any]:
							__magic_name__    :     Tuple     		=      ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size				)

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

							__magic_name__    :     int     		=      None
							if self.use_token_type_ids:
													__magic_name__    :     Optional[Any]     		=      ids_tensor([self.batch_size, self.seq_length]    ,     self.type_vocab_size				)

							__magic_name__    :     Tuple     		=      None
							__magic_name__    :     Optional[Any]     		=      None
							__magic_name__    :     Optional[int]     		=      None
							if self.use_labels:
													__magic_name__    :     Optional[int]     		=      ids_tensor([self.batch_size]    ,     self.type_sequence_label_size				)
													__magic_name__    :     Optional[int]     		=      ids_tensor([self.batch_size, self.seq_length]    ,     self.num_labels				)
													__magic_name__    :     Dict     		=      ids_tensor([self.batch_size]    ,     self.num_choices				)
													__magic_name__    :     Any     		=      ids_tensor([self.batch_size, self.seq_length]    ,     1				)

							__magic_name__    :     List[Any]     		=      self.get_config()

							return (
							    config,
							    input_ids,
							    token_type_ids,
							    input_mask,
							    sequence_labels,
							    token_labels,
							    choice_labels,
							    fake_token_labels,
							)
	def     __magic_name__       (       self				)							->   Optional[int]:
							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     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   str:
							__magic_name__    :     Optional[int]     		=      FunnelModel(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Optional[Any]     		=      model(lowerCAmelCase__    ,     attention_mask=lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__				)
							__magic_name__    :     str     		=      model(lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__				)
							__magic_name__    :     Dict     		=      model(lowerCAmelCase__				)
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.d_model)				)

							__magic_name__    :     Union[str, Any]     		=      False
							__magic_name__    :     Tuple     		=      model(lowerCAmelCase__				)
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.d_model)				)

							__magic_name__    :     Optional[int]     		=      False
							__magic_name__    :     Dict     		=      model(lowerCAmelCase__				)
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.d_model)				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   List[Any]:
							__magic_name__    :     List[str]     		=      FunnelBaseModel(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Dict     		=      model(lowerCAmelCase__    ,     attention_mask=lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__				)
							__magic_name__    :     Optional[Any]     		=      model(lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__				)
							__magic_name__    :     List[str]     		=      model(lowerCAmelCase__				)
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, 2, self.d_model)				)

							__magic_name__    :     str     		=      False
							__magic_name__    :     Optional[int]     		=      model(lowerCAmelCase__				)
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, 3, self.d_model)				)

							__magic_name__    :     List[Any]     		=      False
							__magic_name__    :     Optional[int]     		=      model(lowerCAmelCase__				)
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, 2, self.d_model)				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   int:
							__magic_name__    :     Any     		=      self.num_labels
							__magic_name__    :     Tuple     		=      FunnelForPreTraining(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Optional[int]     		=      model(lowerCAmelCase__    ,     attention_mask=lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__    ,     labels=lowerCAmelCase__				)
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length)				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   List[str]:
							__magic_name__    :     int     		=      FunnelForMaskedLM(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Dict     		=      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     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   Any:
							__magic_name__    :     Tuple     		=      self.num_labels
							__magic_name__    :     str     		=      FunnelForSequenceClassification(lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     int     		=      model(lowerCAmelCase__    ,     attention_mask=lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__    ,     labels=lowerCAmelCase__				)
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   str:
							__magic_name__    :     str     		=      self.num_choices
							__magic_name__    :     int     		=      FunnelForMultipleChoice(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Union[str, Any]     		=      input_ids.unsqueeze(1				).expand(-1    ,     self.num_choices    ,     -1				).contiguous()
							__magic_name__    :     List[Any]     		=      token_type_ids.unsqueeze(1				).expand(-1    ,     self.num_choices    ,     -1				).contiguous()
							__magic_name__    :     Optional[Any]     		=      input_mask.unsqueeze(1				).expand(-1    ,     self.num_choices    ,     -1				).contiguous()
							__magic_name__    :     Union[str, Any]     		=      model(
							    lowerCAmelCase__    ,     attention_mask=lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__    ,     labels=lowerCAmelCase__    ,     )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_choices)				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   Tuple:
							__magic_name__    :     Tuple     		=      self.num_labels
							__magic_name__    :     int     		=      FunnelForTokenClassification(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Union[str, Any]     		=      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     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     )							->   Optional[int]:
							__magic_name__    :     Union[str, Any]     		=      FunnelForQuestionAnswering(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Optional[int]     		=      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     __magic_name__       (       self				)							->   List[Any]:
							__magic_name__    :     Tuple     		=      self.prepare_config_and_inputs()
							(
							    (
							    __magic_name__
							)		,(
							    __magic_name__
							)		,(
							    __magic_name__
							)		,(
							    __magic_name__
							)		,(
							    __magic_name__
							)		,(
							    __magic_name__
							)		,(
							    __magic_name__
							)		,(
							    __magic_name__
							)		,
							)    :     str     		=      config_and_inputs
							__magic_name__    :     Optional[Any]     		=      {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
							return config, inputs_dict





@require_torch
class  snake_case__      (							_lowerCAmelCase		,						_lowerCAmelCase		,						unittest.TestCase   ):
	lowercase__		:  Optional[int]							   =					False
	lowercase__		:  Dict							   =					False
	lowercase__		:  int							   =					(
	    (
	        FunnelModel,
	        FunnelForMaskedLM,
	        FunnelForPreTraining,
	        FunnelForQuestionAnswering,
	        FunnelForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase__		:  Optional[int]							   =					(
	    {
	        '''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     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__=False				)							->   Any:
							__magic_name__    :     Union[str, Any]     		=      super()._prepare_for_class(lowerCAmelCase__    ,     lowerCAmelCase__    ,     return_labels=lowerCAmelCase__				)

							if return_labels:
													if model_class in get_values(lowerCAmelCase__				):
																			__magic_name__    :     List[Any]     		=      torch.zeros(
																			    (self.model_tester.batch_size, self.model_tester.seq_length)    ,     dtype=torch.long    ,     device=lowerCAmelCase__				)
							return inputs_dict
	def     __magic_name__       (       self				)							->   Optional[Any]:
							__magic_name__    :     Any     		=      FunnelModelTester(self				)
							__magic_name__    :     Union[str, Any]     		=      ConfigTester(self    ,     config_class=lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   List[Any]:
							self.config_tester.run_common_tests()
	def     __magic_name__       (       self				)							->   Any:
							__magic_name__    :     Optional[Any]     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Any:
							__magic_name__    :     Optional[Any]     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Tuple:
							__magic_name__    :     Optional[int]     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Tuple:
							__magic_name__    :     Tuple     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Union[str, Any]:
							__magic_name__    :     int     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__				)







	def     __magic_name__       (       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:
																			__magic_name__    :     Optional[int]     		=      getattr(lowerCAmelCase__    ,     lowerCAmelCase__				)
																			weight.data.fill_(3				)





@require_torch
class  snake_case__      (							_lowerCAmelCase		,						unittest.TestCase   ):
	lowercase__		:  Tuple							   =					False
	lowercase__		:  int							   =					False
	lowercase__		:  Optional[int]							   =					(
	    (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
	)
	def     __magic_name__       (       self				)							->   Optional[Any]:
							__magic_name__    :     str     		=      FunnelModelTester(self    ,     base=lowerCAmelCase__				)
							__magic_name__    :     Tuple     		=      ConfigTester(self    ,     config_class=lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   str:
							self.config_tester.run_common_tests()
	def     __magic_name__       (       self				)							->   Optional[int]:
							__magic_name__    :     List[str]     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_base_model(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   str:
							__magic_name__    :     Any     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Tuple:
							__magic_name__    :     Any     		=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   List[str]:
							__magic_name__		,__magic_name__    :     Tuple     		=      self.model_tester.prepare_config_and_inputs_for_common()
							__magic_name__    :     int     		=      True

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







	def     __magic_name__       (       self    ,     lowerCAmelCase__				)							->   Optional[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:
																			__magic_name__    :     Tuple     		=      getattr(lowerCAmelCase__    ,     lowerCAmelCase__				)
																			weight.data.fill_(3				)





@require_torch
@require_sentencepiece
@require_tokenizers
class  snake_case__      (							unittest.TestCase   ):
	def     __magic_name__       (       self				)							->   List[Any]:
							__magic_name__    :     Union[str, Any]     		=      13
							__magic_name__    :     str     		=      7
							__magic_name__    :     Optional[int]     		=      torch.arange(0    ,     batch_size * sequence_length				).long().reshape(lowerCAmelCase__    ,     lowerCAmelCase__				)
							__magic_name__    :     str     		=      [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
							__magic_name__    :     List[Any]     		=      torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths]				)

							__magic_name__    :     Optional[int]     		=      FunnelModel.from_pretrained("""sgugger/funnel-random-tiny"""				)
							__magic_name__    :     List[str]     		=      model(lowerCAmelCase__    ,     token_type_ids=lowerCAmelCase__				)[0].abs()

							__magic_name__    :     Tuple     		=      torch.tensor(2_3_4_4.8_3_5_2				)
							__magic_name__    :     Optional[Any]     		=      torch.tensor(0.8_0_5_2				)
							self.assertTrue(torch.allclose(output.sum()    ,     lowerCAmelCase__    ,     atol=1e-4				)				)
							self.assertTrue(torch.allclose(output.mean()    ,     lowerCAmelCase__    ,     atol=1e-4				)				)

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

							__magic_name__    :     List[Any]     		=      torch.tensor(2_3_4_3.8_4_2_5				)
							__magic_name__    :     Dict     		=      torch.tensor(0.8_0_4_9				)
							self.assertTrue(torch.allclose(output.sum()    ,     lowerCAmelCase__    ,     atol=1e-4				)				)
							self.assertTrue(torch.allclose(output.mean()    ,     lowerCAmelCase__    ,     atol=1e-4				)				)







	@slow
	def     __magic_name__       (       self				)							->   List[Any]:
							__magic_name__    :     Tuple     		=      FunnelTokenizer.from_pretrained("""huggingface/funnel-small"""				)
							__magic_name__    :     Union[str, Any]     		=      FunnelModel.from_pretrained("""huggingface/funnel-small"""				)
							__magic_name__    :     str     		=      tokenizer("""Hello! I am the Funnel Transformer model."""    ,     return_tensors="""pt"""				)
							__magic_name__    :     Optional[Any]     		=      model(**lowerCAmelCase__				)[0]

							__magic_name__    :     List[Any]     		=      torch.tensor(2_3_5.7_2_4_6				)
							__magic_name__    :     List[Any]     		=      torch.tensor(0.0_2_5_6				)
							self.assertTrue(torch.allclose(output.sum()    ,     lowerCAmelCase__    ,     atol=1e-4				)				)
							self.assertTrue(torch.allclose(output.mean()    ,     lowerCAmelCase__    ,     atol=1e-4				)				)
