




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



	"""simple docstring"""


	def __init__(				self		:	Optional[int]				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	List[Any]=13				,    lowerCAmelCase		:	Tuple=7				,    lowerCAmelCase		:	Optional[int]=True				,    lowerCAmelCase		:	Union[str, Any]=True				,    lowerCAmelCase		:	Optional[Any]=True				,    lowerCAmelCase		:	List[Any]=True				,    lowerCAmelCase		:	int=99				,    lowerCAmelCase		:	int=[1, 1, 2]				,    lowerCAmelCase		:	Dict=1				,    lowerCAmelCase		:	Optional[Any]=32				,    lowerCAmelCase		:	Dict=4				,    lowerCAmelCase		:	Any=8				,    lowerCAmelCase		:	List[Any]=37				,    lowerCAmelCase		:	str="gelu_new"				,    lowerCAmelCase		:	List[str]=0.1				,    lowerCAmelCase		:	Union[str, Any]=0.1				,    lowerCAmelCase		:	Tuple=0.0				,    lowerCAmelCase		:	Union[str, Any]=512				,    lowerCAmelCase		:	Dict=3				,    lowerCAmelCase		:	int=0.02				,    lowerCAmelCase		:	Optional[int]=3				,    lowerCAmelCase		:	List[str]=4				,    lowerCAmelCase		:	Any=None				,    lowerCAmelCase		:	List[str]=False				,    )  ->					int:







						"""simple docstring"""







						__UpperCamelCase				:  List[Any]								=			parent
						__UpperCamelCase				:  Any								=			batch_size
						__UpperCamelCase				:  Any								=			seq_length
						__UpperCamelCase				:  Optional[int]								=			is_training
						__UpperCamelCase				:  str								=			use_input_mask
						__UpperCamelCase				:  Optional[int]								=			use_token_type_ids
						__UpperCamelCase				:  int								=			use_labels
						__UpperCamelCase				:  Optional[Any]								=			vocab_size
						__UpperCamelCase				:  List[Any]								=			block_sizes
						__UpperCamelCase				:  List[str]								=			num_decoder_layers
						__UpperCamelCase				:  int								=			d_model
						__UpperCamelCase				:  Optional[int]								=			n_head
						__UpperCamelCase				:  List[Any]								=			d_head
						__UpperCamelCase				:  Optional[int]								=			d_inner
						__UpperCamelCase				:  Any								=			hidden_act
						__UpperCamelCase				:  Tuple								=			hidden_dropout
						__UpperCamelCase				:  str								=			attention_dropout
						__UpperCamelCase				:  Optional[Any]								=			activation_dropout
						__UpperCamelCase				:  Any								=			max_position_embeddings
						__UpperCamelCase				:  Optional[int]								=			type_vocab_size
						__UpperCamelCase				:  List[Any]								=			2
						__UpperCamelCase				:  Any								=			num_labels
						__UpperCamelCase				:  str								=			num_choices
						__UpperCamelCase				:  List[Any]								=			scope
						__UpperCamelCase				:  Union[str, Any]								=			initializer_std

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






	def 				lowerCamelCase__    (				self		:	Optional[int]  )  ->					int:







						"""simple docstring"""







						__UpperCamelCase				:  Union[str, Any]								=			ids_tensor([self.batch_size, self.seq_length]				,    self.vocab_size  )

						__UpperCamelCase				:  Union[str, Any]								=			None
						if self.use_input_mask:
											__UpperCamelCase				:  Optional[Any]								=			ids_tensor([self.batch_size, self.seq_length]				,    vocab_size=2  )

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

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

						__UpperCamelCase				:  str								=			self.get_config()

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






	def 				lowerCamelCase__    (				self		:	Union[str, Any]  )  ->					Union[str, Any]:







						"""simple docstring"""







						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		:	int				,    lowerCAmelCase		:	Optional[int]				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	List[str]				,    lowerCAmelCase		:	Tuple				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	List[Any]				,    )  ->					List[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  Any								=			FunnelModel(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  Optional[Any]								=			model(lowerCAmelCase				,    attention_mask=lowerCAmelCase				,    token_type_ids=lowerCAmelCase  )
						__UpperCamelCase				:  Optional[Any]								=			model(lowerCAmelCase				,    token_type_ids=lowerCAmelCase  )
						__UpperCamelCase				:  Union[str, Any]								=			model(lowerCAmelCase  )
						self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, self.seq_length, self.d_model)  )

						__UpperCamelCase				:  int								=			False
						__UpperCamelCase				:  Dict								=			model(lowerCAmelCase  )
						self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, self.seq_length, self.d_model)  )

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






	def 				lowerCamelCase__    (				self		:	Union[str, Any]				,    lowerCAmelCase		:	Optional[int]				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	Optional[int]				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	Union[str, Any]				,    )  ->					Union[str, Any]:







						"""simple docstring"""







						__UpperCamelCase				:  List[str]								=			FunnelBaseModel(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  Optional[int]								=			model(lowerCAmelCase				,    attention_mask=lowerCAmelCase				,    token_type_ids=lowerCAmelCase  )
						__UpperCamelCase				:  str								=			model(lowerCAmelCase				,    token_type_ids=lowerCAmelCase  )
						__UpperCamelCase				:  Optional[int]								=			model(lowerCAmelCase  )
						self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, 2, self.d_model)  )

						__UpperCamelCase				:  List[Any]								=			False
						__UpperCamelCase				:  Any								=			model(lowerCAmelCase  )
						self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, 3, self.d_model)  )

						__UpperCamelCase				:  List[Any]								=			False
						__UpperCamelCase				:  int								=			model(lowerCAmelCase  )
						self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, 2, self.d_model)  )






	def 				lowerCamelCase__    (				self		:	Any				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Tuple				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	List[str]				,    )  ->					Optional[int]:







						"""simple docstring"""







						__UpperCamelCase				:  str								=			self.num_labels
						__UpperCamelCase				:  Optional[int]								=			FunnelForPreTraining(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  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 				lowerCamelCase__    (				self		:	Any				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	Tuple				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	List[Any]				,    )  ->					str:







						"""simple docstring"""







						__UpperCamelCase				:  List[str]								=			FunnelForMaskedLM(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  str								=			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 				lowerCamelCase__    (				self		:	Tuple				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	Tuple				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Optional[int]				,    lowerCAmelCase		:	Tuple				,    lowerCAmelCase		:	List[str]				,    )  ->					Optional[int]:







						"""simple docstring"""







						__UpperCamelCase				:  Tuple								=			self.num_labels
						__UpperCamelCase				:  int								=			FunnelForSequenceClassification(lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  Dict								=			model(lowerCAmelCase				,    attention_mask=lowerCAmelCase				,    token_type_ids=lowerCAmelCase				,    labels=lowerCAmelCase  )
						self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.num_labels)  )






	def 				lowerCamelCase__    (				self		:	Dict				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	int				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	int				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	int				,    )  ->					str:







						"""simple docstring"""







						__UpperCamelCase				:  str								=			self.num_choices
						__UpperCamelCase				:  Optional[int]								=			FunnelForMultipleChoice(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  Union[str, Any]								=			input_ids.unsqueeze(1  ).expand(-1				,    self.num_choices				,    -1  ).contiguous()
						__UpperCamelCase				:  Any								=			token_type_ids.unsqueeze(1  ).expand(-1				,    self.num_choices				,    -1  ).contiguous()
						__UpperCamelCase				:  Tuple								=			input_mask.unsqueeze(1  ).expand(-1				,    self.num_choices				,    -1  ).contiguous()
						__UpperCamelCase				:  Dict								=			model(
						    lowerCAmelCase				,    attention_mask=lowerCAmelCase				,    token_type_ids=lowerCAmelCase				,    labels=lowerCAmelCase				,    )
						self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.num_choices)  )






	def 				lowerCamelCase__    (				self		:	Tuple				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	List[str]				,    lowerCAmelCase		:	int				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	List[str]				,    lowerCAmelCase		:	int				,    )  ->					Dict:







						"""simple docstring"""







						__UpperCamelCase				:  Union[str, Any]								=			self.num_labels
						__UpperCamelCase				:  List[str]								=			FunnelForTokenClassification(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  Tuple								=			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 				lowerCamelCase__    (				self		:	Any				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	List[Any]				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Optional[Any]				,    lowerCAmelCase		:	int				,    )  ->					int:







						"""simple docstring"""







						__UpperCamelCase				:  Any								=			FunnelForQuestionAnswering(config=lowerCAmelCase  )
						model.to(lowerCAmelCase  )
						model.eval()
						__UpperCamelCase				:  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 				lowerCamelCase__    (				self		:	Union[str, Any]  )  ->					int:







						"""simple docstring"""







						__UpperCamelCase				:  Optional[Any]								=			self.prepare_config_and_inputs()
						(
						    (
						    __UpperCamelCase
						)			, (
						    __UpperCamelCase
						)			, (
						    __UpperCamelCase
						)			, (
						    __UpperCamelCase
						)			, (
						    __UpperCamelCase
						)			, (
						    __UpperCamelCase
						)			, (
						    __UpperCamelCase
						)			, (
						    __UpperCamelCase
						)			, 
						)				:  Any								=			config_and_inputs
						__UpperCamelCase				:  List[str]								=			{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
						return config, inputs_dict






@require_torch
class       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase  ,     _UpperCamelCase  ,     unittest.TestCase      ):



	"""simple docstring"""


	__magic_name__      :					int			  =		False
	__magic_name__      :					int			  =		False
	__magic_name__      :					List[Any]			  =		(
	    (
	        FunnelModel,
	        FunnelForMaskedLM,
	        FunnelForPreTraining,
	        FunnelForQuestionAnswering,
	        FunnelForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	__magic_name__      :					Tuple			  =		(
	    {
	        '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		:	Tuple				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Any				,    lowerCAmelCase		:	Tuple=False  )  ->					Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  Union[str, Any]								=			super()._prepare_for_class(lowerCAmelCase				,    lowerCAmelCase				,    return_labels=lowerCAmelCase  )

						if return_labels:
											if model_class in get_values(lowerCAmelCase  ):
																__UpperCamelCase				:  Optional[int]								=			torch.zeros(
																    (self.model_tester.batch_size, self.model_tester.seq_length)				,    dtype=torch.long				,    device=lowerCAmelCase  )
						return inputs_dict






	def 				lowerCamelCase__    (				self		:	List[str]  )  ->					List[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  List[str]								=			FunnelModelTester(self  )
						__UpperCamelCase				:  int								=			ConfigTester(self				,    config_class=lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Union[str, Any]  )  ->					Union[str, Any]:







						"""simple docstring"""







						self.config_tester.run_common_tests()






	def 				lowerCamelCase__    (				self		:	int  )  ->					List[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  Any								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Dict  )  ->					Any:







						"""simple docstring"""







						__UpperCamelCase				:  Dict								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Dict  )  ->					Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  Tuple								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Tuple  )  ->					List[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  int								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Optional[Any]  )  ->					str:







						"""simple docstring"""







						__UpperCamelCase				:  int								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Dict				,    lowerCAmelCase		:	List[str]  )  ->					Tuple:







						"""simple docstring"""







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






@require_torch
class       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase  ,     unittest.TestCase      ):



	"""simple docstring"""


	__magic_name__      :					int			  =		False
	__magic_name__      :					Optional[Any]			  =		False
	__magic_name__      :					Any			  =		(
	    (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
	)






	def 				lowerCamelCase__    (				self		:	Union[str, Any]  )  ->					Any:







						"""simple docstring"""







						__UpperCamelCase				:  Union[str, Any]								=			FunnelModelTester(self				,    base=lowerCAmelCase  )
						__UpperCamelCase				:  Dict								=			ConfigTester(self				,    config_class=lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	List[str]  )  ->					Tuple:







						"""simple docstring"""







						self.config_tester.run_common_tests()






	def 				lowerCamelCase__    (				self		:	Optional[Any]  )  ->					str:







						"""simple docstring"""







						__UpperCamelCase				:  Dict								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_base_model(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Tuple  )  ->					str:







						"""simple docstring"""







						__UpperCamelCase				:  Optional[Any]								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	int  )  ->					Tuple:







						"""simple docstring"""







						__UpperCamelCase				:  Dict								=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Dict  )  ->					List[Any]:







						"""simple docstring"""







						__UpperCamelCase			, __UpperCamelCase				:  int								=			self.model_tester.prepare_config_and_inputs_for_common()
						__UpperCamelCase				:  Optional[int]								=			True

						for model_class in self.all_model_classes:
											if model_class.__name__ == "FunnelBaseModel":
																continue
											__UpperCamelCase				:  List[Any]								=			model_class(lowerCAmelCase  )
											model.to(lowerCAmelCase  )
											model.train()
											__UpperCamelCase				:  Any								=			self._prepare_for_class(lowerCAmelCase				,    lowerCAmelCase				,    return_labels=lowerCAmelCase  )
											__UpperCamelCase				:  Optional[int]								=			model(**lowerCAmelCase  ).loss
											loss.backward()






	def 				lowerCamelCase__    (				self		:	Optional[Any]				,    lowerCAmelCase		:	str  )  ->					int:







						"""simple docstring"""







						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:
																__UpperCamelCase				:  Any								=			getattr(lowerCAmelCase				,    lowerCAmelCase  )
																weight.data.fill_(3  )






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



	"""simple docstring"""


	def 				lowerCamelCase__    (				self		:	Dict  )  ->					Union[str, Any]:







						"""simple docstring"""







						__UpperCamelCase				:  int								=			13
						__UpperCamelCase				:  Tuple								=			7
						__UpperCamelCase				:  List[Any]								=			torch.arange(0				,    batch_size * sequence_length  ).long().reshape(lowerCAmelCase				,    lowerCAmelCase  )
						__UpperCamelCase				:  List[str]								=			[0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
						__UpperCamelCase				:  Any								=			torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths]  )

						__UpperCamelCase				:  str								=			FunnelModel.from_pretrained("""sgugger/funnel-random-tiny"""  )
						__UpperCamelCase				:  List[str]								=			model(lowerCAmelCase				,    token_type_ids=lowerCAmelCase  )[0].abs()

						__UpperCamelCase				:  Tuple								=			torch.tensor(23_44.83_52  )
						__UpperCamelCase				:  Tuple								=			torch.tensor(0.80_52  )
						self.assertTrue(torch.allclose(output.sum()				,    lowerCAmelCase				,    atol=1E-4  )  )
						self.assertTrue(torch.allclose(output.mean()				,    lowerCAmelCase				,    atol=1E-4  )  )

						__UpperCamelCase				:  Union[str, Any]								=			torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]]  )
						__UpperCamelCase				:  Dict								=			model(lowerCAmelCase				,    attention_mask=lowerCAmelCase				,    token_type_ids=lowerCAmelCase  )[0].abs()

						__UpperCamelCase				:  Any								=			torch.tensor(23_43.84_25  )
						__UpperCamelCase				:  Tuple								=			torch.tensor(0.80_49  )
						self.assertTrue(torch.allclose(output.sum()				,    lowerCAmelCase				,    atol=1E-4  )  )
						self.assertTrue(torch.allclose(output.mean()				,    lowerCAmelCase				,    atol=1E-4  )  )






	@slow
	def 				lowerCamelCase__    (				self		:	str  )  ->					Dict:







						"""simple docstring"""







						__UpperCamelCase				:  Dict								=			FunnelTokenizer.from_pretrained("""huggingface/funnel-small"""  )
						__UpperCamelCase				:  str								=			FunnelModel.from_pretrained("""huggingface/funnel-small"""  )
						__UpperCamelCase				:  Optional[int]								=			tokenizer("""Hello! I am the Funnel Transformer model."""				,    return_tensors="""pt"""  )
						__UpperCamelCase				:  str								=			model(**lowerCAmelCase  )[0]

						__UpperCamelCase				:  str								=			torch.tensor(2_35.72_46  )
						__UpperCamelCase				:  Optional[Any]								=			torch.tensor(0.02_56  )
						self.assertTrue(torch.allclose(output.sum()				,    lowerCAmelCase				,    atol=1E-4  )  )
						self.assertTrue(torch.allclose(output.mean()				,    lowerCAmelCase				,    atol=1E-4  )  )












import logging
import os
import sys
from dataclasses import dataclass, field
from typing import List, Optional

import torch
from datasets import Dataset
from torch import nn
from tqdm.auto import tqdm

from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
    utils,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


a__		    =    '''
Distills an NLI-based zero-shot classifier to a smaller, more efficient model with a fixed set of candidate class
names. Useful for speeding up zero-shot classification in cases where labeled training data is not available, but
when only a single fixed set of classes is needed. Takes a teacher NLI model, student classifier model, unlabeled
dataset, and set of K possible class names. Yields a single classifier with K outputs corresponding to the provided
class names.
'''

a__		    =    logging.getLogger(__name__)


@dataclass
class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


	__magic_name__      :					Optional[str]			  =		field(
	    default='roberta-large-mnli'  ,     metadata={'help': 'The NLI/zero-shot teacher model to be distilled.'}      )
	__magic_name__      :					Optional[str]			  =		field(
	    default='This example is {}.'  ,     metadata={
	        'help': (
	            'Template used to turn class names into mock hypotheses for teacher NLI model. Must include {{}}'
	            'where class name is inserted.'
	        )
	    }  ,     )
	__magic_name__      :					Optional[int]			  =		field(
	    default=32  ,     metadata={'help': 'Batch size for generating teacher predictions.'}      )
	__magic_name__      :					Optional[bool]			  =		field(
	    default=_UpperCamelCase  ,     metadata={
	        'help': (
	            'Allow multiple classes to be true rather than forcing them to sum to 1 (sometimes called'
	            'multi-class multi-label classification).'
	        )
	    }  ,     )
	__magic_name__      :					Optional[float]			  =		field(
	    default=1.0  ,     metadata={'help': 'Temperature applied to teacher softmax for distillation.'}      )






@dataclass
class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


	__magic_name__      :					Optional[str]			  =		field(
	    default='distilbert-base-uncased'  ,     metadata={'help': 'The NLI/zero-shot teacher model to be distilled.'}      )






@dataclass
class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


	__magic_name__      :					str			  =		field(metadata={'help': 'Text file with one unlabeled instance per line.'}      )
	__magic_name__      :					str			  =		field(metadata={'help': 'Text file with one class name per line.'}      )
	__magic_name__      :					bool			  =		field(
	    default=_UpperCamelCase  ,     metadata={'help': 'Whether to use one of the fast tokenizer (backed by the Rust tokenizers library) or not.'}  ,     )






@dataclass
class       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase      ):



	"""simple docstring"""


	__magic_name__      :					Optional[str]			  =		field(
	    default=_UpperCamelCase  ,     metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'}  ,     )
	__magic_name__      :					int			  =		field(
	    default=32  ,     metadata={'help': 'Batch size per GPU/TPU core/CPU for training.'}      )
	__magic_name__      :					int			  =		field(
	    default=128  ,     metadata={'help': 'Batch size per GPU/TPU core/CPU for evaluation.'}      )
	__magic_name__      :					float			  =		field(default=1.0  ,     metadata={'help': 'Total number of training epochs to perform.'}      )
	__magic_name__      :					bool			  =		field(default=_UpperCamelCase  ,     metadata={'help': 'Whether to run training of student model.'}      )
	__magic_name__      :					bool			  =		field(
	    default=_UpperCamelCase  ,     metadata={
	        'help': (
	            'Whether to evaluate the agreement of the final student predictions and the teacher predictions'
	            'after training.'
	        )
	    }  ,     )
	__magic_name__      :					Optional[int]			  =		field(
	    default=0  ,     metadata={
	        'help': (
	            'Limit the total amount of checkpoints.'
	            'Deletes the older checkpoints in the output_dir. Default is 0 (no checkpoints).'
	        )
	    }  ,     )






class       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase      ):



	"""simple docstring"""


	def 				lowerCamelCase__    (				self		:	Any				,    lowerCAmelCase		:	int				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	Tuple=False  )  ->					Any:







						"""simple docstring"""







						__UpperCamelCase				:  List[Any]								=			inputs["""labels"""]
						__UpperCamelCase				:  List[Any]								=			model(inputs["""input_ids"""]				,    attention_mask=inputs["""attention_mask"""]  )
						__UpperCamelCase				:  Optional[Any]								=			outputs[0]

						__UpperCamelCase				:  List[str]								=			-torch.sum(target_p * logits.log_softmax(dim=-1  )				,    axis=-1  ).mean()

						if return_outputs:
											return loss, outputs

						return loss






def 							A__   (snake_case      :		Optional[int]							)    ->	List[Any]:
					__UpperCamelCase				:  Union[str, Any]								=			[]
					with open(snake_case		,  """r"""							) as f:
										for line in f:
															__UpperCamelCase				:  Tuple								=			line.strip()
															if len(snake_case							) > 0:
																				lines.append(snake_case							)
					return lines





def 							A__   (snake_case      :		Optional[int]		,  snake_case      :		Optional[Any]		,  snake_case      :		str							)    ->	str:
					__UpperCamelCase				:  Union[str, Any]								=			[]
					__UpperCamelCase				:  List[str]								=			[]
					for example in examples:
										for name in class_names:
															premises.append(snake_case							)
															hypotheses.append(hypothesis_template.format(snake_case							)							)
					return premises, hypotheses





def 							A__   (snake_case      :		Optional[Any]							)    ->	int:
					for label, ind in config.labelaid.items():
										if label.lower().startswith("""entail"""							):
															return ind
					logger.warning("""Could not identify entailment dimension from teacher config label2id. Setting to -1."""							)
					return -1





def 							A__   (snake_case      :		str		,  snake_case      :		List[str]		,  snake_case      :		List[str]		,  snake_case      :		str		,  snake_case      :		int		,  snake_case      :		float		,  snake_case      :		bool		,  snake_case      :		bool		,  snake_case      :		bool		,  snake_case      :		bool		,  )    ->	List[Any]:
					__UpperCamelCase				:  Any								=			AutoModelForSequenceClassification.from_pretrained(snake_case							)
					__UpperCamelCase				:  str								=			model.config
					if not no_cuda and torch.cuda.is_available():
										__UpperCamelCase				:  List[Any]								=			nn.DataParallel(model.cuda()							)
										batch_size *= len(model.device_ids							)
					__UpperCamelCase				:  Optional[int]								=			AutoTokenizer.from_pretrained(snake_case		,  use_fast=snake_case							)

					__UpperCamelCase			, __UpperCamelCase				:  int								=			get_premise_hypothesis_pairs(snake_case		,  snake_case		,  snake_case							)
					__UpperCamelCase				:  Any								=			[]

					for i in tqdm(range(0		,  len(snake_case							)		,  snake_case							)							):
										__UpperCamelCase				:  List[str]								=			premises[i : i + batch_size]
										__UpperCamelCase				:  Dict								=			hypotheses[i : i + batch_size]

										__UpperCamelCase				:  Any								=			tokenizer(
										    snake_case		,  snake_case		,  padding=snake_case		,  truncation="""only_first"""		,  return_tensors="""pt"""		,  )

										with torch.cuda.amp.autocast(enabled=snake_case							):
															with torch.no_grad():
																				__UpperCamelCase				:  Tuple								=			model(**snake_case							)
										logits.append(outputs.logits.detach().cpu().float()							)

					__UpperCamelCase				:  Tuple								=			get_entailment_id(snake_case							)
					__UpperCamelCase				:  List[Any]								=			-1 if entail_id == 0 else 0
					__UpperCamelCase				:  List[Any]								=			torch.cat(snake_case		,  dim=0							)  # N*K x 3
					__UpperCamelCase				:  str								=			logits.reshape(len(snake_case							)		,  len(snake_case							)		,  -1							)[..., [contr_id, entail_id]]  # N x K x 2

					if multi_label:
										# softmax over (contr, entail) logits for each class independently
										__UpperCamelCase				:  Optional[int]								=			(nli_logits / temperature).softmax(-1							)
					else:
										# softmax over entail logits across classes s.t. class probabilities sum to 1.
										__UpperCamelCase				:  Any								=			(nli_logits / temperature).softmax(1							)

					return nli_prob[..., 1]  # N x K





def 							A__   ()    ->	Optional[Any]:
					__UpperCamelCase				:  Dict								=			HfArgumentParser(
					    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)		,  description=snake_case		,  )

					if len(sys.argv							) == 2 and sys.argv[1].endswith(""".json"""							):
										# If we pass only one argument to the script and it's the path to a json file,
										# let's parse it to get our arguments.
										__UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase				:  Tuple								=			parser.parse_json_file(
										    json_file=os.path.abspath(sys.argv[1]							)							)
					else:
										__UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase				:  List[Any]								=			parser.parse_args_into_dataclasses()

					# Detecting last checkpoint.
					__UpperCamelCase				:  Union[str, Any]								=			None
					if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
										__UpperCamelCase				:  Union[str, Any]								=			get_last_checkpoint(training_args.output_dir							)
										if last_checkpoint is None and len(os.listdir(training_args.output_dir							)							) > 0:
															raise ValueError(
															    F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
															    """Use --overwrite_output_dir to overcome."""							)
										elif last_checkpoint is not None:
															logger.info(
															    F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
															    """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""							)

    # Setup logging
					logging.basicConfig(
					    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""		,  datefmt="""%m/%d/%Y %H:%M:%S"""		,  handlers=[logging.StreamHandler(sys.stdout							)]		,  )
					logger.setLevel(logging.INFO if is_main_process(training_args.local_rank							) else logging.WARN							)

					# Log on each process the small summary:
					logger.warning(
					    F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
					    + F'''distributed training: {bool(training_args.local_rank != -1							)}, 16-bits training: {training_args.fpaa}'''							)
					# Set the verbosity to info of the Transformers logger (on main process only):
					if is_main_process(training_args.local_rank							):
										utils.logging.set_verbosity_info()
										utils.logging.enable_default_handler()
										utils.logging.enable_explicit_format()

					if training_args.local_rank != -1:
										raise ValueError("""Distributed training is not currently supported."""							)
					if training_args.tpu_num_cores is not None:
										raise ValueError("""TPU acceleration is not currently supported."""							)

					logger.info(F'''Training/evaluation parameters {training_args}'''							)

					# Set seed before initializing model.
					set_seed(training_args.seed							)

					# 1. read in data
					__UpperCamelCase				:  Union[str, Any]								=			read_lines(data_args.data_file							)
					__UpperCamelCase				:  int								=			read_lines(data_args.class_names_file							)

					# 2. get teacher predictions and load into dataset
					logger.info("""Generating predictions from zero-shot teacher model"""							)
					__UpperCamelCase				:  List[Any]								=			get_teacher_predictions(
					    teacher_args.teacher_name_or_path		,  snake_case		,  snake_case		,  teacher_args.hypothesis_template		,  teacher_args.teacher_batch_size		,  teacher_args.temperature		,  teacher_args.multi_label		,  data_args.use_fast_tokenizer		,  training_args.no_cuda		,  training_args.fpaa		,  )
					__UpperCamelCase				:  Any								=			Dataset.from_dict(
					    {
					        """text""": examples,
					        """labels""": teacher_soft_preds,
					    }							)

					# 3. create student
					logger.info("""Initializing student model"""							)
					__UpperCamelCase				:  List[str]								=			AutoModelForSequenceClassification.from_pretrained(
					    student_args.student_name_or_path		,  num_labels=len(snake_case							)							)
					__UpperCamelCase				:  Tuple								=			AutoTokenizer.from_pretrained(student_args.student_name_or_path		,  use_fast=data_args.use_fast_tokenizer							)
					__UpperCamelCase				:  int								=			dict(enumerate(snake_case							)							)
					__UpperCamelCase				:  List[str]								=			{label: i for i, label in enumerate(snake_case							)}

					# 4. train student on teacher predictions
					__UpperCamelCase				:  Tuple								=			dataset.map(snake_case		,  input_columns="""text"""							)
					dataset.set_format("""torch"""							)

					def compute_metrics(snake_case      :		List[Any]		,  snake_case      :		Optional[int]=False							):
										__UpperCamelCase				:  Any								=			p.predictions.argmax(-1							)
										__UpperCamelCase				:  List[str]								=			p.label_ids.argmax(-1							)  # "label_ids" are actually distributions
										return {"agreement": (preds == proxy_labels).mean().item()}

					__UpperCamelCase				:  List[str]								=			DistillationTrainer(
					    model=snake_case		,  tokenizer=snake_case		,  args=snake_case		,  train_dataset=snake_case		,  compute_metrics=snake_case		,  )

					if training_args.do_train:
										logger.info("""Training student model on teacher predictions"""							)
										trainer.train()

					if training_args.do_eval:
										__UpperCamelCase				:  List[str]								=			trainer.evaluate(eval_dataset=snake_case							)["""eval_agreement"""]
										logger.info(F'''Agreement of student and teacher predictions: {agreement * 1_00:0.2f}%'''							)

					trainer.save_model()


if __name__ == "__main__":
	main()






