



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 						__a (     SCREAMING_SNAKE_CASE				):



	def __init__(						self							:    Optional[int]				,	snake_case_							:    Dict				,	snake_case_							:    Tuple=13				,	snake_case_							:    str=7				,	snake_case_							:    Any=True				,	snake_case_							:    Union[str, Any]=True				,	snake_case_							:    Union[str, Any]=False				,	snake_case_							:    int=True				,	snake_case_							:    Any=99				,	snake_case_							:    List[str]=32				,	snake_case_							:    Union[str, Any]=5				,	snake_case_							:    Optional[int]=4				,	snake_case_							:    Any=37				,	snake_case_							:    Optional[Any]="gelu"				,	snake_case_							:    Union[str, Any]=0.1				,	snake_case_							:    int=0.1				,	snake_case_							:    Optional[int]=5_12				,	snake_case_							:    Tuple=16				,	snake_case_							:    Tuple=2				,	snake_case_							:    Optional[Any]=0.0_2				,	snake_case_							:    Union[str, Any]=3				,	snake_case_							:    str=4				,	snake_case_							:    Optional[Any]=None				,	)->							Optional[int]:
						__lowerCAmelCase	   =parent
						__lowerCAmelCase	   =batch_size
						__lowerCAmelCase	   =seq_length
						__lowerCAmelCase	   =is_training
						__lowerCAmelCase	   =use_input_mask
						__lowerCAmelCase	   =use_token_type_ids
						__lowerCAmelCase	   =use_labels
						__lowerCAmelCase	   =vocab_size
						__lowerCAmelCase	   =hidden_size
						__lowerCAmelCase	   =num_hidden_layers
						__lowerCAmelCase	   =num_attention_heads
						__lowerCAmelCase	   =intermediate_size
						__lowerCAmelCase	   =hidden_act
						__lowerCAmelCase	   =hidden_dropout_prob
						__lowerCAmelCase	   =attention_probs_dropout_prob
						__lowerCAmelCase	   =max_position_embeddings
						__lowerCAmelCase	   =type_vocab_size
						__lowerCAmelCase	   =type_sequence_label_size
						__lowerCAmelCase	   =initializer_range
						__lowerCAmelCase	   =num_labels
						__lowerCAmelCase	   =num_choices
						__lowerCAmelCase	   =scope



	def 		UpperCamelCase							(						self							:    Dict)->							List[Any]:
						__lowerCAmelCase	   =ids_tensor([self.batch_size, self.seq_length]				,	self.vocab_size)

						__lowerCAmelCase	   =None
						if self.use_input_mask:
											__lowerCAmelCase	   =random_attention_mask([self.batch_size, self.seq_length])

						__lowerCAmelCase	   =None
						__lowerCAmelCase	   =None
						__lowerCAmelCase	   =None
						if self.use_labels:
											__lowerCAmelCase	   =ids_tensor([self.batch_size]				,	self.type_sequence_label_size)
											__lowerCAmelCase	   =ids_tensor([self.batch_size, self.seq_length]				,	self.num_labels)
											__lowerCAmelCase	   =ids_tensor([self.batch_size]				,	self.num_choices)

						__lowerCAmelCase	   =self.get_config()

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



	def 		UpperCamelCase							(						self							:    Optional[int])->							Optional[Any]:
						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 		UpperCamelCase							(						self							:    Dict				,	snake_case_							:    int				,	snake_case_							:    List[Any]				,	snake_case_							:    Optional[Any]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    List[str])->							Optional[int]:
						__lowerCAmelCase	   =DistilBertModel(config=snake_case_)
						model.to(snake_case_)
						model.eval()
						__lowerCAmelCase	   =model(snake_case_				,	snake_case_)
						__lowerCAmelCase	   =model(snake_case_)
						self.parent.assertEqual(result.last_hidden_state.shape				,	(self.batch_size, self.seq_length, self.hidden_size))



	def 		UpperCamelCase							(						self							:    List[Any]				,	snake_case_							:    Optional[int]				,	snake_case_							:    int				,	snake_case_							:    Optional[int]				,	snake_case_							:    Optional[Any]				,	snake_case_							:    Optional[Any]				,	snake_case_							:    Union[str, Any])->							Union[str, Any]:
						__lowerCAmelCase	   =DistilBertForMaskedLM(config=snake_case_)
						model.to(snake_case_)
						model.eval()
						__lowerCAmelCase	   =model(snake_case_				,	attention_mask=snake_case_				,	labels=snake_case_)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.seq_length, self.vocab_size))



	def 		UpperCamelCase							(						self							:    Tuple				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Optional[int]				,	snake_case_							:    Any				,	snake_case_							:    Any				,	snake_case_							:    List[Any])->							Any:
						__lowerCAmelCase	   =DistilBertForQuestionAnswering(config=snake_case_)
						model.to(snake_case_)
						model.eval()
						__lowerCAmelCase	   =model(
						    snake_case_				,	attention_mask=snake_case_				,	start_positions=snake_case_				,	end_positions=snake_case_)
						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 		UpperCamelCase							(						self							:    Dict				,	snake_case_							:    Any				,	snake_case_							:    str				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    List[Any]				,	snake_case_							:    Tuple				,	snake_case_							:    Union[str, Any])->							Tuple:
						__lowerCAmelCase	   =self.num_labels
						__lowerCAmelCase	   =DistilBertForSequenceClassification(snake_case_)
						model.to(snake_case_)
						model.eval()
						__lowerCAmelCase	   =model(snake_case_				,	attention_mask=snake_case_				,	labels=snake_case_)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.num_labels))



	def 		UpperCamelCase							(						self							:    Tuple				,	snake_case_							:    Any				,	snake_case_							:    List[str]				,	snake_case_							:    Optional[int]				,	snake_case_							:    List[Any]				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    List[Any])->							Dict:
						__lowerCAmelCase	   =self.num_labels
						__lowerCAmelCase	   =DistilBertForTokenClassification(config=snake_case_)
						model.to(snake_case_)
						model.eval()

						__lowerCAmelCase	   =model(snake_case_				,	attention_mask=snake_case_				,	labels=snake_case_)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.seq_length, self.num_labels))



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



	def 		UpperCamelCase							(						self							:    Any)->							Union[str, Any]:
						__lowerCAmelCase	   =self.prepare_config_and_inputs()
						((__lowerCAmelCase)   ,	(__lowerCAmelCase)   ,	(__lowerCAmelCase)   ,	(__lowerCAmelCase)   ,	(__lowerCAmelCase)   ,	(__lowerCAmelCase))	   =config_and_inputs
						__lowerCAmelCase	   ={"""input_ids""": input_ids, """attention_mask""": input_mask}
						return config, inputs_dict






@require_torch
class 						__a (     SCREAMING_SNAKE_CASE	,    SCREAMING_SNAKE_CASE	,    unittest.TestCase				):
	SCREAMING_SNAKE_CASE       =       (
	    (
	        DistilBertModel,
	        DistilBertForMaskedLM,
	        DistilBertForMultipleChoice,
	        DistilBertForQuestionAnswering,
	        DistilBertForSequenceClassification,
	        DistilBertForTokenClassification,
	    )
	    if is_torch_available()
	    else None
	)
	SCREAMING_SNAKE_CASE       =       (
	    {
	        "feature-extraction": DistilBertModel,
	        "fill-mask": DistilBertForMaskedLM,
	        "question-answering": DistilBertForQuestionAnswering,
	        "text-classification": DistilBertForSequenceClassification,
	        "token-classification": DistilBertForTokenClassification,
	        "zero-shot": DistilBertForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE       =       True
	SCREAMING_SNAKE_CASE       =       True
	SCREAMING_SNAKE_CASE       =       True
	SCREAMING_SNAKE_CASE       =       True



	def 		UpperCamelCase							(						self							:    Optional[int])->							Union[str, Any]:
						__lowerCAmelCase	   =DistilBertModelTester(self)
						__lowerCAmelCase	   =ConfigTester(self				,	config_class=snake_case_				,	dim=37)



	def 		UpperCamelCase							(						self							:    Optional[int])->							List[str]:
						self.config_tester.run_common_tests()



	def 		UpperCamelCase							(						self							:    List[Any])->							Dict:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_distilbert_model(*snake_case_)



	def 		UpperCamelCase							(						self							:    Dict)->							Optional[Any]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_distilbert_for_masked_lm(*snake_case_)



	def 		UpperCamelCase							(						self							:    int)->							Union[str, Any]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_distilbert_for_question_answering(*snake_case_)



	def 		UpperCamelCase							(						self							:    Union[str, Any])->							List[Any]:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_distilbert_for_sequence_classification(*snake_case_)



	def 		UpperCamelCase							(						self							:    Dict)->							Tuple:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_distilbert_for_token_classification(*snake_case_)



	def 		UpperCamelCase							(						self							:    List[str])->							Tuple:
						__lowerCAmelCase	   =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_distilbert_for_multiple_choice(*snake_case_)



	@slow
	def 		UpperCamelCase							(						self							:    Tuple)->							Any:
						for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCAmelCase	   =DistilBertModel.from_pretrained(snake_case_)
											self.assertIsNotNone(snake_case_)



	@slow
	@require_torch_gpu
	def 		UpperCamelCase							(						self							:    List[str])->							str:
						__lowerCAmelCase   ,	__lowerCAmelCase	   =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

											__lowerCAmelCase	   =True
											__lowerCAmelCase	   =model_class(config=snake_case_)

											__lowerCAmelCase	   =self._prepare_for_class(snake_case_				,	snake_case_)
											__lowerCAmelCase	   =torch.jit.trace(
											    snake_case_				,	(inputs_dict["""input_ids"""].to("""cpu"""), inputs_dict["""attention_mask"""].to("""cpu""")))

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






@require_torch
class 						__a (     unittest.TestCase				):



	@slow
	def 		UpperCamelCase							(						self							:    Union[str, Any])->							str:
						__lowerCAmelCase	   =DistilBertModel.from_pretrained("""distilbert-base-uncased""")
						__lowerCAmelCase	   =torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
						__lowerCAmelCase	   =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
						with torch.no_grad():
											__lowerCAmelCase	   =model(snake_case_				,	attention_mask=snake_case_)[0]
						__lowerCAmelCase	   =torch.Size((1, 11, 7_68))
						self.assertEqual(output.shape				,	snake_case_)
						__lowerCAmelCase	   =torch.tensor(
						    [[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]])

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









def 					__lowerCAmelCase		(  __lowerCamelCase	:    int = 3				,   __lowerCamelCase	:    int = 7				,   __lowerCamelCase	:    int = 1000000	)  ->						int:
					__lowerCAmelCase	   =0
					__lowerCAmelCase	   =1

					for current_denominator in range(1				,   limit + 1	):
										__lowerCAmelCase	   =current_denominator * numerator // denominator
										if current_denominator % denominator == 0:
															current_numerator -= 1
										if current_numerator * max_denominator > current_denominator * max_numerator:
															__lowerCAmelCase	   =current_numerator
															__lowerCAmelCase	   =current_denominator
					return max_numerator


if __name__ == "__main__":
				print(solution(numerator=3, denominator=7, limit=1_00_00_00))




