





"""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 					_a		:






				def __init__(					self						:       int,					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Optional[Any]=1_3,					lowerCAmelCase__						:       Optional[int]=7,					lowerCAmelCase__						:       int=True,					lowerCAmelCase__						:       Dict=True,					lowerCAmelCase__						:       List[Any]=True,					lowerCAmelCase__						:       Tuple=True,					lowerCAmelCase__						:       Union[str, Any]=9_9,					lowerCAmelCase__						:       int=[1, 1, 2],					lowerCAmelCase__						:       int=1,					lowerCAmelCase__						:       Dict=3_2,					lowerCAmelCase__						:       int=4,					lowerCAmelCase__						:       Dict=8,					lowerCAmelCase__						:       Optional[int]=3_7,					lowerCAmelCase__						:       List[str]="gelu_new",					lowerCAmelCase__						:       Dict=0.1,					lowerCAmelCase__						:       Optional[int]=0.1,					lowerCAmelCase__						:       Dict=0.0,					lowerCAmelCase__						:       Optional[int]=5_1_2,					lowerCAmelCase__						:       List[Any]=3,					lowerCAmelCase__						:       List[Any]=0.02,					lowerCAmelCase__						:       Tuple=3,					lowerCAmelCase__						:       int=4,					lowerCAmelCase__						:       Union[str, Any]=None,					lowerCAmelCase__						:       Tuple=False,					)      -> Tuple:




										'''simple docstring'''



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

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






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       ids_tensor([self.batch_size, self.seq_length],					self.vocab_size				)

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

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

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

										_UpperCamelCase     :   Any      =       self.get_config()

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






				def 							snake_case      (					self						:       List[str]				)      -> Optional[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 							snake_case      (					self						:       List[Any],					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       int,					)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   str      =       FunnelModel(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   int      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       model(lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.d_model)				)

										_UpperCamelCase     :   Tuple      =       False
										_UpperCamelCase     :   Any      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.d_model)				)

										_UpperCamelCase     :   Optional[int]      =       False
										_UpperCamelCase     :   List[Any]      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.d_model)				)






				def 							snake_case      (					self						:       Optional[int],					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       List[Any],					)      -> Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   int      =       FunnelBaseModel(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   List[str]      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   Union[str, Any]      =       model(lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)
										_UpperCamelCase     :   str      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, 2, self.d_model)				)

										_UpperCamelCase     :   str      =       False
										_UpperCamelCase     :   Dict      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, 3, self.d_model)				)

										_UpperCamelCase     :   Tuple      =       False
										_UpperCamelCase     :   Optional[int]      =       model(lowerCAmelCase__				)
										self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, 2, self.d_model)				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.num_labels
										_UpperCamelCase     :   List[str]      =       FunnelForPreTraining(config=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.seq_length)				)






				def 							snake_case      (					self						:       Optional[int],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       Optional[int],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       str,					)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       FunnelForMaskedLM(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   List[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.vocab_size)				)






				def 							snake_case      (					self						:       Dict,					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Dict,					lowerCAmelCase__						:       str,					)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.num_labels
										_UpperCamelCase     :   List[str]      =       FunnelForSequenceClassification(lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   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_labels)				)






				def 							snake_case      (					self						:       Optional[int],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Any,					)      -> Optional[Any]:




										'''simple docstring'''



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






				def 							snake_case      (					self						:       Any,					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Tuple,					lowerCAmelCase__						:       Tuple,					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       int,					lowerCAmelCase__						:       List[Any],					lowerCAmelCase__						:       Union[str, Any],					)      -> List[str]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.num_labels
										_UpperCamelCase     :   List[Any]      =       FunnelForTokenClassification(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, self.num_labels)				)






				def 							snake_case      (					self						:       Tuple,					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       List[str],					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       Union[str, Any],					lowerCAmelCase__						:       str,					)      -> List[str]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       FunnelForQuestionAnswering(config=lowerCAmelCase__				)
										model.to(lowerCAmelCase__				)
										model.eval()
										_UpperCamelCase     :   Dict      =       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 							snake_case      (					self						:       int				)      -> List[str]:




										'''simple docstring'''



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




@require_torch
class 					_a		( _lowerCAmelCase      ,							_lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       False
				UpperCamelCase								=       False
				UpperCamelCase								=       (
				    (
				        FunnelModel,
				        FunnelForMaskedLM,
				        FunnelForPreTraining,
				        FunnelForQuestionAnswering,
				        FunnelForTokenClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				UpperCamelCase								=       (
				    {
				        '''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 							snake_case      (					self						:       Union[str, Any],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Any,					lowerCAmelCase__						:       List[str]=False				)      -> Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase     :   str      =       super()._prepare_for_class(lowerCAmelCase__,					lowerCAmelCase__,					return_labels=lowerCAmelCase__				)

										if return_labels:
																if model_class in get_values(lowerCAmelCase__				):
																						_UpperCamelCase     :   List[str]      =       torch.zeros(
																						    (self.model_tester.batch_size, self.model_tester.seq_length),					dtype=torch.long,					device=lowerCAmelCase__				)
										return inputs_dict






				def 							snake_case      (					self						:       Any				)      -> str:




										'''simple docstring'''



										_UpperCamelCase     :   Tuple      =       FunnelModelTester(self				)
										_UpperCamelCase     :   List[Any]      =       ConfigTester(self,					config_class=lowerCAmelCase__				)






				def 							snake_case      (					self						:       Optional[Any]				)      -> List[Any]:




										'''simple docstring'''



										self.config_tester.run_common_tests()






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




										'''simple docstring'''



										_UpperCamelCase     :   int      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       List[str]				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       Optional[Any]				)      -> List[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       Optional[int]				)      -> Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       int,					lowerCAmelCase__						:       int				)      -> Any:




										'''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     :   str      =       getattr(lowerCAmelCase__,					lowerCAmelCase__				)
																						weight.data.fill_(3				)




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






				def 							snake_case      (					self						:       Tuple				)      -> str:




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       FunnelModelTester(self,					base=lowerCAmelCase__				)
										_UpperCamelCase     :   Optional[Any]      =       ConfigTester(self,					config_class=lowerCAmelCase__				)






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




										'''simple docstring'''



										self.config_tester.run_common_tests()






				def 							snake_case      (					self						:       Any				)      -> int:




										'''simple docstring'''



										_UpperCamelCase     :   Any      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_base_model(*lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       Any				)      -> Any:




										'''simple docstring'''



										_UpperCamelCase     :   Any      =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__				)






				def 							snake_case      (					self						:       int				)      -> Dict:




										'''simple docstring'''



										_UpperCamelCase  ,				_UpperCamelCase     :   Union[str, Any]      =       self.model_tester.prepare_config_and_inputs_for_common()
										_UpperCamelCase     :   Tuple      =       True

										for model_class in self.all_model_classes:
																if model_class.__name__ == "FunnelBaseModel":
																						continue
																_UpperCamelCase     :   Any      =       model_class(lowerCAmelCase__				)
																model.to(lowerCAmelCase__				)
																model.train()
																_UpperCamelCase     :   Union[str, Any]      =       self._prepare_for_class(lowerCAmelCase__,					lowerCAmelCase__,					return_labels=lowerCAmelCase__				)
																_UpperCamelCase     :   Optional[Any]      =       model(**lowerCAmelCase__				).loss
																loss.backward()






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




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






				def 							snake_case      (					self						:       int				)      -> List[str]:




										'''simple docstring'''



										_UpperCamelCase     :   List[Any]      =       1_3
										_UpperCamelCase     :   List[Any]      =       7
										_UpperCamelCase     :   int      =       torch.arange(0,					batch_size * sequence_length				).long().reshape(lowerCAmelCase__,					lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
										_UpperCamelCase     :   Optional[int]      =       torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths]				)

										_UpperCamelCase     :   List[Any]      =       FunnelModel.from_pretrained('''sgugger/funnel-random-tiny'''				)
										_UpperCamelCase     :   str      =       model(lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)[0].abs()

										_UpperCamelCase     :   Optional[Any]      =       torch.tensor(2_344.8_352				)
										_UpperCamelCase     :   Union[str, Any]      =       torch.tensor(0.8_052				)
										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     :   Optional[Any]      =       model(lowerCAmelCase__,					attention_mask=lowerCAmelCase__,					token_type_ids=lowerCAmelCase__				)[0].abs()

										_UpperCamelCase     :   str      =       torch.tensor(2_343.8_425				)
										_UpperCamelCase     :   List[Any]      =       torch.tensor(0.8_049				)
										self.assertTrue(torch.allclose(output.sum(),					lowerCAmelCase__,					atol=1e-4				)				)
										self.assertTrue(torch.allclose(output.mean(),					lowerCAmelCase__,					atol=1e-4				)				)






				@slow
				def 							snake_case      (					self						:       int				)      -> List[str]:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       FunnelTokenizer.from_pretrained('''huggingface/funnel-small'''				)
										_UpperCamelCase     :   Optional[Any]      =       FunnelModel.from_pretrained('''huggingface/funnel-small'''				)
										_UpperCamelCase     :   Tuple      =       tokenizer('''Hello! I am the Funnel Transformer model.''',					return_tensors='''pt'''				)
										_UpperCamelCase     :   Union[str, Any]      =       model(**lowerCAmelCase__				)[0]

										_UpperCamelCase     :   Tuple      =       torch.tensor(235.7_246				)
										_UpperCamelCase     :   Union[str, Any]      =       torch.tensor(0.0_256				)
										self.assertTrue(torch.allclose(output.sum(),					lowerCAmelCase__,					atol=1e-4				)				)
										self.assertTrue(torch.allclose(output.mean(),					lowerCAmelCase__,					atol=1e-4				)				)











import sys
from typing import Tuple

import numpy as np
import torch
from PIL import Image
from torch import nn

from transformers.image_utils import PILImageResampling
from utils import img_tensorize





class        a__      :






		def __init__(      self							, lowercase__							, lowercase__=sys.maxsize						)				->				str:
				__A    =							"bilinear"
				__A    =							max_size
				__A    =							short_edge_length






		def __call__(      self							, lowercase__						)				->				Dict:
				__A    =							[]
				for img in imgs:
						__A ,   __A    =							img.shape[:2]
						# later: provide list and randomly choose index for resize
						__A    =							np.random.randint(self.short_edge_length[0]							, self.short_edge_length[1] + 1						)
						if size == 0:
								return img
						__A    =							size * 1.0 / min(lowercase__							, lowercase__						)
						if h < w:
								__A ,   __A    =							size, scale * w
						else:
								__A ,   __A    =							scale * h, size
						if max(lowercase__							, lowercase__						) > self.max_size:
								__A    =							self.max_size * 1.0 / max(lowercase__							, lowercase__						)
								__A    =							newh * scale
								__A    =							neww * scale
						__A    =							int(neww + 0.5						)
						__A    =							int(newh + 0.5						)

						if img.dtype == np.uinta:
								__A    =							Image.fromarray(lowercase__						)
								__A    =							pil_image.resize((neww, newh)							, PILImageResampling.BILINEAR						)
								__A    =							np.asarray(lowercase__						)
						else:
								__A    =							img.permute(2							, 0							, 1						).unsqueeze(0						)  # 3, 0, 1)  # hw(c) -> nchw
								__A    =							nn.functional.interpolate(
								    lowercase__							, (newh, neww)							, mode=self.interp_method							, align_corners=lowercase__						).squeeze(0						)
						img_augs.append(lowercase__						)

				return img_augs





class        a__      :






		def __init__(      self							, lowercase__						)				->				Union[str, Any]:
				__A    =							ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST]							, cfg.INPUT.MAX_SIZE_TEST						)
				__A    =							cfg.INPUT.FORMAT
				__A    =							cfg.SIZE_DIVISIBILITY
				__A    =							cfg.PAD_VALUE
				__A    =							cfg.INPUT.MAX_SIZE_TEST
				__A    =							cfg.MODEL.DEVICE
				__A    =							torch.tensor(cfg.MODEL.PIXEL_STD						).to(self.device						).view(len(cfg.MODEL.PIXEL_STD						)							, 1							, 1						)
				__A    =							torch.tensor(cfg.MODEL.PIXEL_MEAN						).to(self.device						).view(len(cfg.MODEL.PIXEL_STD						)							, 1							, 1						)
				__A    =							lambda lowercase__						: (x - self.pixel_mean) / self.pixel_std






		def 					_lowerCamelCase					(      self							, lowercase__						)				->				Optional[int]:
				__A    =							tuple(max(lowercase__						) for s in zip(*[img.shape for img in images]						)						)
				__A    =							[im.shape[-2:] for im in images]
				__A    =							[
				    nn.functional.pad(
				        lowercase__							, [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]]							, value=self.pad_value							, )
				    for size, im in zip(lowercase__							, lowercase__						)
				]

				return torch.stack(lowercase__						), torch.tensor(lowercase__						)






		def __call__(      self							, lowercase__							, lowercase__=False						)				->				int:
				with torch.no_grad():
						if not isinstance(lowercase__							, lowercase__						):
								__A    =							[images]
						if single_image:
								assert len(lowercase__						) == 1
						for i in range(len(lowercase__						)						):
								if isinstance(images[i]							, torch.Tensor						):
										images.insert(lowercase__							, images.pop(lowercase__						).to(self.device						).float()						)
								elif not isinstance(images[i]							, torch.Tensor						):
										images.insert(
										    lowercase__							, torch.as_tensor(img_tensorize(images.pop(lowercase__						)							, input_format=self.input_format						)						)
										    .to(self.device						)
										    .float()							, )
            # resize smallest edge
						__A    =							torch.tensor([im.shape[:2] for im in images]						)
						__A    =							self.aug(lowercase__						)
						# transpose images and convert to torch tensors
						# images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
						# now normalize before pad to avoid useless arithmetic
						__A    =							[self.normalizer(lowercase__						) for x in images]
						# now pad them to do the following operations
						__A ,   __A    =							self.pad(lowercase__						)
						# Normalize

						if self.size_divisibility > 0:
								raise NotImplementedError()
						# pad
						__A    =							torch.true_divide(lowercase__							, lowercase__						)
						if single_image:
								return images[0], sizes[0], scales_yx[0]
						else:
								return images, sizes, scales_yx



def      UpperCAmelCase						( lowerCAmelCase__					,     lowerCAmelCase__	):


		'''simple docstring'''

		boxes[:, 0::2] *= scale_yx[:, 1]
		boxes[:, 1::2] *= scale_yx[:, 0]
		return boxes





def      UpperCAmelCase						( lowerCAmelCase__					,     lowerCAmelCase__	):


		'''simple docstring'''

		assert torch.isfinite(lowerCAmelCase__	).all(), "Box tensor contains infinite or NaN!"
		__A ,   __A    =							box_size
		tensor[:, 0].clamp_(min=0					,     max=lowerCAmelCase__	)
		tensor[:, 1].clamp_(min=0					,     max=lowerCAmelCase__	)
		tensor[:, 2].clamp_(min=0					,     max=lowerCAmelCase__	)
		tensor[:, 3].clamp_(min=0					,     max=lowerCAmelCase__	)

