





import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import (
	    DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
	    DistilBertForMaskedLM,
	    DistilBertForMultipleChoice,
	    DistilBertForQuestionAnswering,
	    DistilBertForSequenceClassification,
	    DistilBertForTokenClassification,
	    DistilBertModel,
	)



class    __lowerCAmelCase			(     _a	):






			def __init__(self   ,				__magic_name__   ,				__magic_name__=13   ,				__magic_name__=7   ,				__magic_name__=True   ,				__magic_name__=True   ,				__magic_name__=False   ,				__magic_name__=True   ,				__magic_name__=99   ,				__magic_name__=32   ,				__magic_name__=5   ,				__magic_name__=4   ,				__magic_name__=37   ,				__magic_name__="gelu"   ,				__magic_name__=0.1   ,				__magic_name__=0.1   ,				__magic_name__=512   ,				__magic_name__=16   ,				__magic_name__=2   ,				__magic_name__=0.02   ,				__magic_name__=3   ,				__magic_name__=4   ,				__magic_name__=None   ,				)	->  Dict:


							'''simple docstring'''



							snake_case_		:       List[str]           =    parent
							snake_case_		:       List[Any]           =    batch_size
							snake_case_		:       List[Any]           =    seq_length
							snake_case_		:       List[Any]           =    is_training
							snake_case_		:       Optional[Any]           =    use_input_mask
							snake_case_		:       str           =    use_token_type_ids
							snake_case_		:       List[str]           =    use_labels
							snake_case_		:       int           =    vocab_size
							snake_case_		:       int           =    hidden_size
							snake_case_		:       Optional[Any]           =    num_hidden_layers
							snake_case_		:       Union[str, Any]           =    num_attention_heads
							snake_case_		:       Tuple           =    intermediate_size
							snake_case_		:       int           =    hidden_act
							snake_case_		:       Tuple           =    hidden_dropout_prob
							snake_case_		:       Dict           =    attention_probs_dropout_prob
							snake_case_		:       List[str]           =    max_position_embeddings
							snake_case_		:       List[Any]           =    type_vocab_size
							snake_case_		:       List[str]           =    type_sequence_label_size
							snake_case_		:       Union[str, Any]           =    initializer_range
							snake_case_		:       List[Any]           =    num_labels
							snake_case_		:       Optional[int]           =    num_choices
							snake_case_		:       Any           =    scope






			def      lowerCamelCase    (self       )	->  str:


							'''simple docstring'''



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

							snake_case_		:       List[Any]           =    None
							if self.use_input_mask:
											snake_case_		:       Optional[Any]           =    random_attention_mask([self.batch_size, self.seq_length]       )

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

							snake_case_		:       Dict           =    self.get_config()

							return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






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


							'''simple docstring'''



							return DistilBertConfig(
							    vocab_size=self.vocab_size   ,				dim=self.hidden_size   ,				n_layers=self.num_hidden_layers   ,				n_heads=self.num_attention_heads   ,				hidden_dim=self.intermediate_size   ,				hidden_act=self.hidden_act   ,				dropout=self.hidden_dropout_prob   ,				attention_dropout=self.attention_probs_dropout_prob   ,				max_position_embeddings=self.max_position_embeddings   ,				initializer_range=self.initializer_range   ,				)






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Optional[Any]:


							'''simple docstring'''



							snake_case_		:       str           =    DistilBertModel(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       List[Any]           =    model(__magic_name__   ,				__magic_name__       )
							snake_case_		:       List[Any]           =    model(__magic_name__       )
							self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, self.seq_length, self.hidden_size)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Any:


							'''simple docstring'''



							snake_case_		:       str           =    DistilBertForMaskedLM(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       str           =    model(__magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.seq_length, self.vocab_size)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  int:


							'''simple docstring'''



							snake_case_		:       Optional[int]           =    DistilBertForQuestionAnswering(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       Union[str, Any]           =    model(
							    __magic_name__   ,				attention_mask=__magic_name__   ,				start_positions=__magic_name__   ,				end_positions=__magic_name__       )
							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   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  Any:


							'''simple docstring'''



							snake_case_		:       str           =    self.num_labels
							snake_case_		:       str           =    DistilBertForSequenceClassification(__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       Optional[int]           =    model(__magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  str:


							'''simple docstring'''



							snake_case_		:       Dict           =    self.num_labels
							snake_case_		:       List[Any]           =    DistilBertForTokenClassification(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()

							snake_case_		:       Optional[Any]           =    model(__magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__       )
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.seq_length, self.num_labels)       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )	->  List[str]:


							'''simple docstring'''



							snake_case_		:       Any           =    self.num_choices
							snake_case_		:       List[Any]           =    DistilBertForMultipleChoice(config=__magic_name__       )
							model.to(__magic_name__       )
							model.eval()
							snake_case_		:       int           =    input_ids.unsqueeze(1       ).expand(-1   ,				self.num_choices   ,				-1       ).contiguous()
							snake_case_		:       Optional[int]           =    input_mask.unsqueeze(1       ).expand(-1   ,				self.num_choices   ,				-1       ).contiguous()
							snake_case_		:       Tuple           =    model(
							    __magic_name__   ,				attention_mask=__magic_name__   ,				labels=__magic_name__   ,				)
							self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_choices)       )






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


							'''simple docstring'''



							snake_case_		:       Dict           =    self.prepare_config_and_inputs()
							((snake_case_)     ,				(snake_case_)     ,				(snake_case_)     ,				(snake_case_)     ,				(snake_case_)     ,				(snake_case_))		:       Union[str, Any]           =    config_and_inputs
							snake_case_		:       Optional[int]           =    {'''input_ids''': input_ids, '''attention_mask''': input_mask}
							return config, inputs_dict




@require_torch
class    __lowerCAmelCase			(     _a,	_a,	unittest.TestCase	):
			lowerCamelCase_	:	Optional[int]			     = (
			    (
			        DistilBertModel,
			        DistilBertForMaskedLM,
			        DistilBertForMultipleChoice,
			        DistilBertForQuestionAnswering,
			        DistilBertForSequenceClassification,
			        DistilBertForTokenClassification,
			    )
			    if is_torch_available()
			    else None
			)
			lowerCamelCase_	:	str			     = (
			    {
			        '''feature-extraction''': DistilBertModel,
			        '''fill-mask''': DistilBertForMaskedLM,
			        '''question-answering''': DistilBertForQuestionAnswering,
			        '''text-classification''': DistilBertForSequenceClassification,
			        '''token-classification''': DistilBertForTokenClassification,
			        '''zero-shot''': DistilBertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			lowerCamelCase_	:	Optional[Any]			     = True
			lowerCamelCase_	:	List[Any]			     = True
			lowerCamelCase_	:	int			     = True
			lowerCamelCase_	:	str			     = True






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


							'''simple docstring'''



							snake_case_		:       int           =    DistilBertModelTester(self       )
							snake_case_		:       List[str]           =    ConfigTester(self   ,				config_class=__magic_name__   ,				dim=37       )






			def      lowerCamelCase    (self       )	->  int:


							'''simple docstring'''



							self.config_tester.run_common_tests()






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


							'''simple docstring'''



							snake_case_		:       Union[str, Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_model(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  Any:


							'''simple docstring'''



							snake_case_		:       List[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_masked_lm(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  List[Any]:


							'''simple docstring'''



							snake_case_		:       int           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_question_answering(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  Optional[Any]:


							'''simple docstring'''



							snake_case_		:       Optional[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_sequence_classification(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  List[Any]:


							'''simple docstring'''



							snake_case_		:       Optional[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_token_classification(*__magic_name__       )






			def      lowerCamelCase    (self       )	->  List[str]:


							'''simple docstring'''



							snake_case_		:       Optional[Any]           =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_distilbert_for_multiple_choice(*__magic_name__       )






			@slow
			def      lowerCamelCase    (self       )	->  Tuple:


							'''simple docstring'''



							for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											snake_case_		:       Tuple           =    DistilBertModel.from_pretrained(__magic_name__       )
											self.assertIsNotNone(__magic_name__       )






			@slow
			@require_torch_gpu
			def      lowerCamelCase    (self       )	->  Dict:


							'''simple docstring'''



							snake_case_     ,				snake_case_		:       Optional[int]           =    self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
											# BertForMultipleChoice behaves incorrectly in JIT environments.
											if model_class == DistilBertForMultipleChoice:
															return

											snake_case_		:       List[str]           =    True
											snake_case_		:       Tuple           =    model_class(config=__magic_name__       )

											snake_case_		:       Tuple           =    self._prepare_for_class(__magic_name__   ,				__magic_name__       )
											snake_case_		:       List[str]           =    torch.jit.trace(
											    __magic_name__   ,				(inputs_dict['''input_ids'''].to('''cpu'''       ), inputs_dict['''attention_mask'''].to('''cpu'''       ))       )

											with tempfile.TemporaryDirectory() as tmp:
															torch.jit.save(__magic_name__   ,				os.path.join(__magic_name__   ,				'''traced_model.pt'''       )       )
															snake_case_		:       Union[str, Any]           =    torch.jit.load(os.path.join(__magic_name__   ,				'''traced_model.pt'''       )   ,				map_location=__magic_name__       )
															loaded(inputs_dict['''input_ids'''].to(__magic_name__       )   ,				inputs_dict['''attention_mask'''].to(__magic_name__       )       )




@require_torch
class    __lowerCAmelCase			(     unittest.TestCase	):






			@slow
			def      lowerCamelCase    (self       )	->  Tuple:


							'''simple docstring'''



							snake_case_		:       Tuple           =    DistilBertModel.from_pretrained('''distilbert-base-uncased'''       )
							snake_case_		:       List[Any]           =    torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]       )
							snake_case_		:       Union[str, Any]           =    torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]       )
							with torch.no_grad():
											snake_case_		:       int           =    model(__magic_name__   ,				attention_mask=__magic_name__       )[0]
							snake_case_		:       int           =    torch.Size((1, 11, 768)       )
							self.assertEqual(output.shape   ,				__magic_name__       )
							snake_case_		:       Union[str, Any]           =    torch.tensor(
							    [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]]       )

							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]   ,				__magic_name__   ,				atol=1e-4       )       )




'''simple docstring'''
__SCREAMING_SNAKE_CASE					:				Optional[int]									=		{
    '''a''': '''AAAAA''',
    '''b''': '''AAAAB''',
    '''c''': '''AAABA''',
    '''d''': '''AAABB''',
    '''e''': '''AABAA''',
    '''f''': '''AABAB''',
    '''g''': '''AABBA''',
    '''h''': '''AABBB''',
    '''i''': '''ABAAA''',
    '''j''': '''BBBAA''',
    '''k''': '''ABAAB''',
    '''l''': '''ABABA''',
    '''m''': '''ABABB''',
    '''n''': '''ABBAA''',
    '''o''': '''ABBAB''',
    '''p''': '''ABBBA''',
    '''q''': '''ABBBB''',
    '''r''': '''BAAAA''',
    '''s''': '''BAAAB''',
    '''t''': '''BAABA''',
    '''u''': '''BAABB''',
    '''v''': '''BBBAB''',
    '''w''': '''BABAA''',
    '''x''': '''BABAB''',
    '''y''': '''BABBA''',
    '''z''': '''BABBB''',
    ''' ''': ''' ''',
}


__SCREAMING_SNAKE_CASE					:				Tuple									=		{value: key for key, value in encode_dict.items()}







def       a_				(	UpperCamelCase_ ):
							A_			    =		""
							for letter in word.lower():
														if letter.isalpha() or letter == " ":
																					encoded += encode_dict[letter]
														else:
																					raise Exception("encode() accepts only letters of the alphabet and spaces" )
							return encoded







def       a_				(	UpperCamelCase_ ):
							if set(UpperCamelCase_ ) - {"A", "B", " "} != set():
														raise Exception("decode() accepts only 'A', 'B' and spaces" )
							A_			    =		""
							for word in coded.split():
														while len(UpperCamelCase_ ) != 0:
																					decoded += decode_dict[word[:5]]
																					A_			    =		word[5:]
														decoded += " "
							return decoded.strip()


if __name__ == "__main__":
							from doctest import testmod

							testmod()





