





"""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				)				)





"""simple docstring"""
import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import cached_download, hf_hub_url
from PIL import Image

from transformers import DeformableDetrConfig, DeformableDetrForObjectDetection, DeformableDetrImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
lowercase		:    List[str]			=       logging.get_logger(__name__)


def      lowerCamelCase_     (						lowerCamelCase_			)  ->      str:


					'''simple docstring'''
					if "backbone.0.body" in orig_key:
										__a:    Any		     =       orig_key.replace("""backbone.0.body"""						,					"""backbone.conv_encoder.model"""			)
					if "transformer" in orig_key:
										__a:    str		     =       orig_key.replace("""transformer."""						,					""""""			)
					if "norm1" in orig_key:
										if "encoder" in orig_key:
															__a:    List[str]		     =       orig_key.replace("""norm1"""						,					"""self_attn_layer_norm"""			)
										else:
															__a:    Optional[int]		     =       orig_key.replace("""norm1"""						,					"""encoder_attn_layer_norm"""			)
					if "norm2" in orig_key:
										if "encoder" in orig_key:
															__a:    Union[str, Any]		     =       orig_key.replace("""norm2"""						,					"""final_layer_norm"""			)
										else:
															__a:    str		     =       orig_key.replace("""norm2"""						,					"""self_attn_layer_norm"""			)
					if "norm3" in orig_key:
										__a:    int		     =       orig_key.replace("""norm3"""						,					"""final_layer_norm"""			)
					if "linear1" in orig_key:
										__a:    Dict		     =       orig_key.replace("""linear1"""						,					"""fc1"""			)
					if "linear2" in orig_key:
										__a:    Any		     =       orig_key.replace("""linear2"""						,					"""fc2"""			)
					if "query_embed" in orig_key:
										__a:    Dict		     =       orig_key.replace("""query_embed"""						,					"""query_position_embeddings"""			)
					if "cross_attn" in orig_key:
										__a:    Dict		     =       orig_key.replace("""cross_attn"""						,					"""encoder_attn"""			)

					return orig_key


def      lowerCamelCase_     (						lowerCamelCase_			)  ->      List[str]:


					'''simple docstring'''
					# transformer decoder self-attention layers
					for i in range(6			):
										# read in weights + bias of input projection layer of self-attention
										__a:    Optional[Any]		     =       state_dict.pop(f"""decoder.layers.{i}.self_attn.in_proj_weight"""			)
										__a:    List[str]		     =       state_dict.pop(f"""decoder.layers.{i}.self_attn.in_proj_bias"""			)
										# next, add query, keys and values (in that order) to the state dict
										__a:    Optional[int]		     =       in_proj_weight[:2_56, :]
										__a:    int		     =       in_proj_bias[:2_56]
										__a:    Tuple		     =       in_proj_weight[2_56:5_12, :]
										__a:    Union[str, Any]		     =       in_proj_bias[2_56:5_12]
										__a:    Optional[int]		     =       in_proj_weight[-2_56:, :]
										__a:    Any		     =       in_proj_bias[-2_56:]


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


					'''simple docstring'''
					__a:    List[Any]		     =       """http://images.cocodataset.org/val2017/000000039769.jpg"""
					__a:    Tuple		     =       Image.open(requests.get(lowerCamelCase_						,					stream=lowerCamelCase_			).raw			)

					return im


@torch.no_grad()
def      lowerCamelCase_     (						lowerCamelCase_						,					lowerCamelCase_						,					lowerCamelCase_						,					lowerCamelCase_						,					lowerCamelCase_						,					lowerCamelCase_						,					lowerCamelCase_						,					)  ->      Union[str, Any]:


					'''simple docstring'''
					__a:    Optional[Any]		     =       DeformableDetrConfig()
					# set config attributes
					if single_scale:
										__a:    Optional[int]		     =       1
					__a:    Optional[Any]		     =       dilation
					__a:    Dict		     =       with_box_refine
					__a:    Any		     =       two_stage
					# set labels
					__a:    str		     =       91
					__a:    Dict		     =       """huggingface/label-files"""
					__a:    Tuple		     =       """coco-detection-id2label.json"""
					__a:    Optional[int]		     =       json.load(open(cached_download(hf_hub_url(lowerCamelCase_						,					lowerCamelCase_						,					repo_type="""dataset"""			)			)						,					"""r"""			)			)
					__a:    Union[str, Any]		     =       {int(lowerCamelCase_			): v for k, v in idalabel.items()}
					__a:    Dict		     =       idalabel
					__a:    List[Any]		     =       {v: k for k, v in idalabel.items()}

					# load image processor
					__a:    Tuple		     =       DeformableDetrImageProcessor(format="""coco_detection"""			)

					# prepare image
					__a:    Tuple		     =       prepare_img()
					__a:    Optional[int]		     =       image_processor(images=lowerCamelCase_						,					return_tensors="""pt"""			)
					__a:    Any		     =       encoding["""pixel_values"""]

					logger.info("""Converting model..."""			)

					# load original state dict
					__a:    List[Any]		     =       torch.load(lowerCamelCase_						,					map_location="""cpu"""			)["""model"""]
					# rename keys
					for key in state_dict.copy().keys():
										__a:    Dict		     =       state_dict.pop(lowerCamelCase_			)
										__a:    List[str]		     =       val
					# query, key and value matrices need special treatment
					read_in_q_k_v(lowerCamelCase_			)
					# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
					__a:    Optional[int]		     =       """model."""
					for key in state_dict.copy().keys():
										if not key.startswith("""class_embed"""			) and not key.startswith("""bbox_embed"""			):
															__a:    List[Any]		     =       state_dict.pop(lowerCamelCase_			)
															__a:    Optional[int]		     =       val
    # finally, create HuggingFace model and load state dict
					__a:    List[str]		     =       DeformableDetrForObjectDetection(lowerCamelCase_			)
					model.load_state_dict(lowerCamelCase_			)
					model.eval()

					__a:    List[str]		     =       """cuda""" if torch.cuda.is_available() else """cpu"""
					model.to(lowerCamelCase_			)
					# verify our conversion
					__a:    str		     =       model(pixel_values.to(lowerCamelCase_			)			)

					__a:    Union[str, Any]		     =       torch.tensor(
					    [[-9.6_645, -4.3_449, -5.8_705], [-9.7_035, -3.8_504, -5.0_724], [-10.5_634, -5.3_379, -7.5_116]]			)
					__a:    Union[str, Any]		     =       torch.tensor([[0.8_693, 0.2_289, 0.2_492], [0.3_150, 0.5_489, 0.5_845], [0.5_563, 0.7_580, 0.8_518]]			)

					if single_scale:
										__a:    Optional[Any]		     =       torch.tensor(
										    [[-9.9_051, -4.2_541, -6.4_852], [-9.6_947, -4.0_854, -6.8_033], [-10.0_665, -5.8_470, -7.7_003]]			)
										__a:    Any		     =       torch.tensor([[0.7_292, 0.4_991, 0.5_532], [0.7_959, 0.2_426, 0.4_236], [0.7_582, 0.3_518, 0.4_451]]			)

					if single_scale and dilation:
										__a:    Dict		     =       torch.tensor(
										    [[-8.9_652, -4.1_074, -5.6_635], [-9.0_596, -4.9_447, -6.6_075], [-10.1_178, -4.5_275, -6.2_671]]			)
										__a:    int		     =       torch.tensor([[0.7_665, 0.4_130, 0.4_769], [0.8_364, 0.1_841, 0.3_391], [0.6_261, 0.3_895, 0.7_978]]			)

					if with_box_refine:
										__a:    List[str]		     =       torch.tensor(
										    [[-8.8_895, -5.4_187, -6.8_153], [-8.4_706, -6.1_668, -7.6_184], [-9.0_042, -5.5_359, -6.9_141]]			)
										__a:    Optional[int]		     =       torch.tensor([[0.7_828, 0.2_208, 0.4_323], [0.0_892, 0.5_996, 0.1_319], [0.5_524, 0.6_389, 0.8_914]]			)

					if with_box_refine and two_stage:
										__a:    List[Any]		     =       torch.tensor(
										    [[-6.7_108, -4.3_213, -6.3_777], [-8.9_014, -6.1_799, -6.7_240], [-6.9_315, -4.4_735, -6.2_298]]			)
										__a:    Union[str, Any]		     =       torch.tensor([[0.2_583, 0.5_499, 0.4_683], [0.7_652, 0.9_068, 0.4_882], [0.5_490, 0.2_763, 0.0_564]]			)

					print("""Logits:"""						,					outputs.logits[0, :3, :3]			)

					assert torch.allclose(outputs.logits[0, :3, :3]						,					expected_logits.to(lowerCamelCase_			)						,					atol=1e-4			)
					assert torch.allclose(outputs.pred_boxes[0, :3, :3]						,					expected_boxes.to(lowerCamelCase_			)						,					atol=1e-4			)

					print("""Everything ok!"""			)

					# Save model and image processor
					logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}..."""			)
					Path(lowerCamelCase_			).mkdir(exist_ok=lowerCamelCase_			)
					model.save_pretrained(lowerCamelCase_			)
					image_processor.save_pretrained(lowerCamelCase_			)

					# Push to hub
					if push_to_hub:
										__a:    Dict		     =       """deformable-detr"""
										model_name += "-single-scale" if single_scale else ""
										model_name += "-dc5" if dilation else ""
										model_name += "-with-box-refine" if with_box_refine else ""
										model_name += "-two-stage" if two_stage else ""
										print("""Pushing model to hub..."""			)
										model.push_to_hub(repo_path_or_name=lowerCamelCase_						,					organization="""nielsr"""						,					commit_message="""Add model"""			)


if __name__ == "__main__":
			lowercase		:    int			=       argparse.ArgumentParser()

			parser.add_argument(
			    '--checkpoint_path',
			    type=str,
			    default='/home/niels/checkpoints/deformable_detr/r50_deformable_detr-checkpoint.pth',
			    help='Path to Pytorch checkpoint (.pth file) you\'d like to convert.',
			)
			parser.add_argument('--single_scale', action='store_true', help='Whether to set config.num_features_levels = 1.')
			parser.add_argument('--dilation', action='store_true', help='Whether to set config.dilation=True.')
			parser.add_argument('--with_box_refine', action='store_true', help='Whether to set config.with_box_refine=True.')
			parser.add_argument('--two_stage', action='store_true', help='Whether to set config.two_stage=True.')
			parser.add_argument(
			    '--pytorch_dump_folder_path',
			    default=None,
			    type=str,
			    required=True,
			    help='Path to the folder to output PyTorch model.',
			)
			parser.add_argument(
			    '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
			)
			lowercase		:    Union[str, Any]			=       parser.parse_args()
			convert_deformable_detr_checkpoint(
			    args.checkpoint_path,
			    args.single_scale,
			    args.dilation,
			    args.with_box_refine,
			    args.two_stage,
			    args.pytorch_dump_folder_path,
			    args.push_to_hub,
			)
