

'''simple docstring'''



import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp
def 						__lowerCamelCase	(       )	->							List[Any]:






						"""simple docstring"""





						A__					:       int     =ArgumentParser(
						    description=(
						        """PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"""
						    )	)

						# Optional arguments for the launch helper
						parser.add_argument("""--num_cores""",		type=__snake_case,		default=1,		help="""Number of TPU cores to use (1 or 8)."""	)

						# positional
						parser.add_argument(
						    """training_script""",		type=__snake_case,		help=(
						        """The full path to the single TPU training """
						        """program/script to be launched in parallel, """
						        """followed by all the arguments for the """
						        """training script"""
						    ),		)

						# rest from the training program
						parser.add_argument("""training_script_args""",		nargs=__snake_case	)

						return parser.parse_args()
def 						__lowerCamelCase	(       )	->							Dict:






						"""simple docstring"""





						A__					:       Any     =parse_args()

						# Import training_script as a module.
						A__					:       Optional[int]     =Path(args.training_script	)
						sys.path.append(str(script_fpath.parent.resolve()	)	)
						A__					:       Optional[int]     =script_fpath.stem
						A__					:       Optional[Any]     =importlib.import_module(__snake_case	)

						# Patch sys.argv
						A__					:       str     =[args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores	)]

						xmp.spawn(mod._mp_fn,		args=(),		nprocs=args.num_cores	)


if __name__ == "__main__":
		main()




'''simple docstring'''



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			(  lowercase_						):



			'''simple docstring'''






			def __init__(				self	:						Dict		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						List[str]=13		,      lowerCAmelCase_	:						Dict=7		,      lowerCAmelCase_	:						Union[str, Any]=True		,      lowerCAmelCase_	:						str=True		,      lowerCAmelCase_	:						int=False		,      lowerCAmelCase_	:						int=True		,      lowerCAmelCase_	:						int=99		,      lowerCAmelCase_	:						str=32		,      lowerCAmelCase_	:						str=5		,      lowerCAmelCase_	:						List[Any]=4		,      lowerCAmelCase_	:						Dict=37		,      lowerCAmelCase_	:						Optional[Any]="gelu"		,      lowerCAmelCase_	:						Tuple=0.1		,      lowerCAmelCase_	:						Dict=0.1		,      lowerCAmelCase_	:						str=5_12		,      lowerCAmelCase_	:						Dict=16		,      lowerCAmelCase_	:						Any=2		,      lowerCAmelCase_	:						Dict=0.02		,      lowerCAmelCase_	:						Optional[int]=3		,      lowerCAmelCase_	:						List[Any]=4		,      lowerCAmelCase_	:						Optional[int]=None		,      )      ->		List[str]:





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


			def lowercase__						(				self	:						int			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Dict     =ids_tensor([self.batch_size, self.seq_length]		,      self.vocab_size			)

									A__					:       List[str]     =None
									if self.use_input_mask:
															A__					:       Union[str, Any]     =random_attention_mask([self.batch_size, self.seq_length]			)

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

									A__					:       str     =self.get_config()

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


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





									'''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 lowercase__						(				self	:						Optional[Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						List[Any]			)      ->		str:





									'''simple docstring'''
									A__					:       Union[str, Any]     =DistilBertModel(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Dict     =model(lowerCAmelCase_		,      lowerCAmelCase_			)
									A__					:       List[str]     =model(lowerCAmelCase_			)
									self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size)			)


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Any			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Union[str, Any]     =DistilBertForMaskedLM(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Union[str, Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.vocab_size)			)


			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Optional[Any]			)      ->		Dict:





									'''simple docstring'''
									A__					:       Dict     =DistilBertForQuestionAnswering(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Tuple     =model(
									    lowerCAmelCase_		,      attention_mask=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 lowercase__						(				self	:						Optional[int]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Dict			)      ->		Tuple:





									'''simple docstring'''
									A__					:       List[Any]     =self.num_labels
									A__					:       Dict     =DistilBertForSequenceClassification(lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       Union[str, Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)			)


			def lowercase__						(				self	:						str		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						List[Any]			)      ->		int:





									'''simple docstring'''
									A__					:       Optional[int]     =self.num_labels
									A__					:       Union[str, Any]     =DistilBertForTokenClassification(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()

									A__					:       List[Any]     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.num_labels)			)


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





									'''simple docstring'''
									A__					:       int     =self.num_choices
									A__					:       Tuple     =DistilBertForMultipleChoice(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       int     =input_ids.unsqueeze(1			).expand(-1		,      self.num_choices		,      -1			).contiguous()
									A__					:       int     =input_mask.unsqueeze(1			).expand(-1		,      self.num_choices		,      -1			).contiguous()
									A__					:       Tuple     =model(
									    lowerCAmelCase_		,      attention_mask=lowerCAmelCase_		,      labels=lowerCAmelCase_		,      )
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_choices)			)



			def lowercase__						(				self	:						Tuple			)      ->		Optional[Any]:





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



@require_torch
class lowerCamelCase			(  lowercase_	,						lowercase_	,						unittest.TestCase						):



			'''simple docstring'''






			__snake_case        =	(
			    (
			        DistilBertModel,
			        DistilBertForMaskedLM,
			        DistilBertForMultipleChoice,
			        DistilBertForQuestionAnswering,
			        DistilBertForSequenceClassification,
			        DistilBertForTokenClassification,
			    )
			    if is_torch_available()
			    else None
			)
			__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 {}
			)
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	True


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





									'''simple docstring'''
									A__					:       Any     =DistilBertModelTester(self			)
									A__					:       Tuple     =ConfigTester(self		,      config_class=lowerCAmelCase_		,      dim=37			)


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





									'''simple docstring'''
									self.config_tester.run_common_tests()


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





									'''simple docstring'''
									A__					:       int     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_model(*lowerCAmelCase_			)


			def lowercase__						(				self	:						Any			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Tuple     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_masked_lm(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       str     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_question_answering(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       Any     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       Dict     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_token_classification(*lowerCAmelCase_			)


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





									'''simple docstring'''
									A__					:       List[Any]     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowerCAmelCase_			)


			@slow
			def lowercase__						(				self	:						Union[str, Any]			)      ->		Dict:





									'''simple docstring'''
									for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															A__					:       Optional[int]     =DistilBertModel.from_pretrained(lowerCAmelCase_			)
															self.assertIsNotNone(lowerCAmelCase_			)



			@slow
			@require_torch_gpu
			def lowercase__						(				self	:						Tuple			)      ->		Any:





									'''simple docstring'''
									A__   ,						A__					:       List[str]     =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

															A__					:       Any     =True
															A__					:       Optional[Any]     =model_class(config=lowerCAmelCase_			)

															A__					:       Dict     =self._prepare_for_class(lowerCAmelCase_		,      lowerCAmelCase_			)
															A__					:       Optional[int]     =torch.jit.trace(
															    lowerCAmelCase_		,      (inputs_dict["""input_ids"""].to("""cpu"""			), inputs_dict["""attention_mask"""].to("""cpu"""			))			)

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



@require_torch
class lowerCamelCase			(  unittest.TestCase						):



			'''simple docstring'''






			@slow
			def lowercase__						(				self	:						List[Any]			)      ->		List[Any]:





									'''simple docstring'''
									A__					:       List[str]     =DistilBertModel.from_pretrained("""distilbert-base-uncased"""			)
									A__					:       Optional[Any]     =torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]			)
									A__					:       int     =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
									with torch.no_grad():
															A__					:       Any     =model(lowerCAmelCase_		,      attention_mask=lowerCAmelCase_			)[0]
									A__					:       Tuple     =torch.Size((1, 11, 7_68)			)
									self.assertEqual(output.shape		,      lowerCAmelCase_			)
									A__					:       Optional[int]     =torch.tensor(
									    [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]			)

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

