

"""simple docstring"""





import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
		import jax.numpy as jnp

		from transformers.models.distilbert.modeling_flax_distilbert import (
		    FlaxDistilBertForMaskedLM,
		    FlaxDistilBertForMultipleChoice,
		    FlaxDistilBertForQuestionAnswering,
		    FlaxDistilBertForSequenceClassification,
		    FlaxDistilBertForTokenClassification,
		    FlaxDistilBertModel,
		)



class __lowerCAmelCase				(					unittest.TestCase      ):




			"""simple docstring"""







			def __init__(				self						:					Dict       ,   _snake_case						:					Any       ,   _snake_case						:					List[str]=13       ,   _snake_case						:					List[str]=7       ,   _snake_case						:					int=True       ,   _snake_case						:					Dict=True       ,   _snake_case						:					Dict=True       ,   _snake_case						:					List[Any]=True       ,   _snake_case						:					Union[str, Any]=99       ,   _snake_case						:					List[str]=32       ,   _snake_case						:					Optional[int]=5       ,   _snake_case						:					int=4       ,   _snake_case						:					str=37       ,   _snake_case						:					Union[str, Any]="gelu"       ,   _snake_case						:					int=0.1       ,   _snake_case						:					Union[str, Any]=0.1       ,   _snake_case						:					Optional[Any]=512       ,   _snake_case						:					str=16       ,   _snake_case						:					str=2       ,   _snake_case						:					List[str]=0.0_2       ,   _snake_case						:					List[Any]=4       ,   )      -> Optional[Any]:







								"""simple docstring"""
								A_				 =						parent
								A_				 =						batch_size
								A_				 =						seq_length
								A_				 =						is_training
								A_				 =						use_attention_mask
								A_				 =						use_token_type_ids
								A_				 =						use_labels
								A_				 =						vocab_size
								A_				 =						hidden_size
								A_				 =						num_hidden_layers
								A_				 =						num_attention_heads
								A_				 =						intermediate_size
								A_				 =						hidden_act
								A_				 =						hidden_dropout_prob
								A_				 =						attention_probs_dropout_prob
								A_				 =						max_position_embeddings
								A_				 =						type_vocab_size
								A_				 =						type_sequence_label_size
								A_				 =						initializer_range
								A_				 =						num_choices




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







								"""simple docstring"""
								A_				 =						ids_tensor([self.batch_size, self.seq_length]       ,   self.vocab_size	)

								A_				 =						None
								if self.use_attention_mask:
													A_				 =						random_attention_mask([self.batch_size, self.seq_length]	)

								A_				 =						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       ,   tie_weights_=_snake_case       ,   )

								return config, input_ids, attention_mask






			def      lowerCamelCase__     (				self						:					Dict	)      -> Dict:







								"""simple docstring"""
								A_				 =						self.prepare_config_and_inputs()
								A_ ,    A_ ,    A_				 =						config_and_inputs
								A_				 =						{"input_ids": input_ids, "attention_mask": attention_mask}
								return config, inputs_dict





@require_flax
class __lowerCAmelCase				(					_lowercase     ,				unittest.TestCase      ):




			"""simple docstring"""







			snake_case	      =				(
			    (
			        FlaxDistilBertModel,
			        FlaxDistilBertForMaskedLM,
			        FlaxDistilBertForMultipleChoice,
			        FlaxDistilBertForQuestionAnswering,
			        FlaxDistilBertForSequenceClassification,
			        FlaxDistilBertForTokenClassification,
			        FlaxDistilBertForQuestionAnswering,
			    )
			    if is_flax_available()
			    else ()
			)




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







								"""simple docstring"""
								A_				 =						FlaxDistilBertModelTester(self	)






			@slow
			def      lowerCamelCase__     (				self						:					Any	)      -> Optional[int]:







								"""simple docstring"""
								for model_class_name in self.all_model_classes:
													A_				 =						model_class_name.from_pretrained("distilbert-base-uncased"	)
													A_				 =						model(np.ones((1, 1)	)	)
													self.assertIsNotNone(_snake_case	)





@require_flax
class __lowerCAmelCase				(					unittest.TestCase      ):




			"""simple docstring"""







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







								"""simple docstring"""
								A_				 =						FlaxDistilBertModel.from_pretrained("distilbert-base-uncased"	)
								A_				 =						np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]	)
								A_				 =						np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]	)
								A_				 =						model(_snake_case       ,   attention_mask=_snake_case	)[0]
								A_				 =						(1, 11, 768)
								self.assertEqual(output.shape       ,   _snake_case	)
								A_				 =						np.array([[[-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(jnp.allclose(output[:, 1:4, 1:4]       ,   _snake_case       ,   atol=1e-4	)	)






"""simple docstring"""





from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand
def 							A_     (__a				):

					'''simple docstring'''





					return ConvertCommand(
					    args.model_type				,   args.tf_checkpoint				,   args.pytorch_dump_output				,   args.config				,   args.finetuning_task_name				)


UpperCamelCase_					:						Tuple				= '''
transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires
TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.
'''




class __lowerCAmelCase				(					_lowercase      ):




			"""simple docstring"""







			@staticmethod
			def      lowerCamelCase__     (				_snake_case						:					ArgumentParser	)      -> Union[str, Any]:







								"""simple docstring"""
								A_				 =						parser.add_parser(
								    "convert"       ,   help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints."       ,   )
								train_parser.add_argument("--model_type"       ,   type=_snake_case       ,   required=_snake_case       ,   help="Model's type."	)
								train_parser.add_argument(
								    "--tf_checkpoint"       ,   type=_snake_case       ,   required=_snake_case       ,   help="TensorFlow checkpoint path or folder."	)
								train_parser.add_argument(
								    "--pytorch_dump_output"       ,   type=_snake_case       ,   required=_snake_case       ,   help="Path to the PyTorch saved model output."	)
								train_parser.add_argument("--config"       ,   type=_snake_case       ,   default=""       ,   help="Configuration file path or folder."	)
								train_parser.add_argument(
								    "--finetuning_task_name"       ,   type=_snake_case       ,   default=_snake_case       ,   help="Optional fine-tuning task name if the TF model was a finetuned model."       ,   )
								train_parser.set_defaults(func=_snake_case	)




			def __init__(				self						:					str       ,   _snake_case						:					str       ,   _snake_case						:					str       ,   _snake_case						:					str       ,   _snake_case						:					str       ,   _snake_case						:					str       ,   *_snake_case						:					Optional[int]       ,   )      -> Union[str, Any]:







								"""simple docstring"""
								A_				 =						logging.get_logger("transformers-cli/converting"	)

								self._logger.info(F'Loading model {model_type}'	)
								A_				 =						model_type
								A_				 =						tf_checkpoint
								A_				 =						pytorch_dump_output
								A_				 =						config
								A_				 =						finetuning_task_name






			def      lowerCamelCase__     (				self						:					Tuple	)      -> Dict:







								"""simple docstring"""
								if self._model_type == "albert":
													try:
																		from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
																		    convert_tf_checkpoint_to_pytorch,
																		)
													except ImportError:
																		raise ImportError(_snake_case	)

													convert_tf_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output	)
								elif self._model_type == "bert":
													try:
																		from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
																		    convert_tf_checkpoint_to_pytorch,
																		)
													except ImportError:
																		raise ImportError(_snake_case	)

													convert_tf_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output	)
								elif self._model_type == "funnel":
													try:
																		from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
																		    convert_tf_checkpoint_to_pytorch,
																		)
													except ImportError:
																		raise ImportError(_snake_case	)

													convert_tf_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output	)
								elif self._model_type == "t5":
													try:
																		from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
													except ImportError:
																		raise ImportError(_snake_case	)

													convert_tf_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output	)
								elif self._model_type == "gpt":
													from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
													    convert_openai_checkpoint_to_pytorch,
													)

													convert_openai_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output	)
								elif self._model_type == "transfo_xl":
													try:
																		from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
																		    convert_transfo_xl_checkpoint_to_pytorch,
																		)
													except ImportError:
																		raise ImportError(_snake_case	)

													if "ckpt" in self._tf_checkpoint.lower():
																		A_				 =						self._tf_checkpoint
																		A_				 =						""
													else:
																		A_				 =						self._tf_checkpoint
																		A_				 =						""
													convert_transfo_xl_checkpoint_to_pytorch(
													    _snake_case       ,   self._config       ,   self._pytorch_dump_output       ,   _snake_case	)
								elif self._model_type == "gpt2":
													try:
																		from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
																		    convert_gpta_checkpoint_to_pytorch,
																		)
													except ImportError:
																		raise ImportError(_snake_case	)

													convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output	)
								elif self._model_type == "xlnet":
													try:
																		from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
																		    convert_xlnet_checkpoint_to_pytorch,
																		)
													except ImportError:
																		raise ImportError(_snake_case	)

													convert_xlnet_checkpoint_to_pytorch(
													    self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output       ,   self._finetuning_task_name	)
								elif self._model_type == "xlm":
													from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
													    convert_xlm_checkpoint_to_pytorch,
													)

													convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._pytorch_dump_output	)
								elif self._model_type == "lxmert":
													from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
													    convert_lxmert_checkpoint_to_pytorch,
													)

													convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._pytorch_dump_output	)
								elif self._model_type == "rembert":
													from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
													    convert_rembert_tf_checkpoint_to_pytorch,
													)

													convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint       ,   self._config       ,   self._pytorch_dump_output	)
								else:
													raise ValueError(
													    "--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]"	)




