
"""simple docstring"""





import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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 (
		    MODEL_FOR_PRETRAINING_MAPPING,
		    AlbertForMaskedLM,
		    AlbertForMultipleChoice,
		    AlbertForPreTraining,
		    AlbertForQuestionAnswering,
		    AlbertForSequenceClassification,
		    AlbertForTokenClassification,
		    AlbertModel,
		)
		from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST



class __lowerCAmelCase				:




			"""simple docstring"""







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







								"""simple docstring"""
								A_				 =						parent
								A_				 =						batch_size
								A_				 =						seq_length
								A_				 =						is_training
								A_				 =						use_input_mask
								A_				 =						use_token_type_ids
								A_				 =						use_labels
								A_				 =						vocab_size
								A_				 =						embedding_size
								A_				 =						hidden_size
								A_				 =						num_hidden_layers
								A_				 =						num_hidden_groups
								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_labels
								A_				 =						num_choices
								A_				 =						scope




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







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

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

								A_				 =						None
								if self.use_token_type_ids:
													A_				 =						ids_tensor([self.batch_size, self.seq_length]       ,   self.type_vocab_size	)

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

								A_				 =						self.get_config()

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




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







								"""simple docstring"""
								return AlbertConfig(
								    vocab_size=self.vocab_size       ,   hidden_size=self.hidden_size       ,   num_hidden_layers=self.num_hidden_layers       ,   num_attention_heads=self.num_attention_heads       ,   intermediate_size=self.intermediate_size       ,   hidden_act=self.hidden_act       ,   hidden_dropout_prob=self.hidden_dropout_prob       ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,   max_position_embeddings=self.max_position_embeddings       ,   type_vocab_size=self.type_vocab_size       ,   initializer_range=self.initializer_range       ,   num_hidden_groups=self.num_hidden_groups       ,   )




			def      lowerCamelCase__     (				self						:					Optional[int]       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					List[Any]       ,   _snake_case						:					Any       ,   _snake_case						:					List[Any]       ,   _snake_case						:					int       ,   _snake_case						:					Dict	)      -> Union[str, Any]:







								"""simple docstring"""
								A_				 =						AlbertModel(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(_snake_case       ,   attention_mask=_snake_case       ,   token_type_ids=_snake_case	)
								A_				 =						model(_snake_case       ,   token_type_ids=_snake_case	)
								A_				 =						model(_snake_case	)
								self.parent.assertEqual(result.last_hidden_state.shape       ,   (self.batch_size, self.seq_length, self.hidden_size)	)
								self.parent.assertEqual(result.pooler_output.shape       ,   (self.batch_size, self.hidden_size)	)




			def      lowerCamelCase__     (				self						:					Union[str, Any]       ,   _snake_case						:					int       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					int       ,   _snake_case						:					List[str]       ,   _snake_case						:					List[Any]       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					Any	)      -> Any:







								"""simple docstring"""
								A_				 =						AlbertForPreTraining(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(
								    _snake_case       ,   attention_mask=_snake_case       ,   token_type_ids=_snake_case       ,   labels=_snake_case       ,   sentence_order_label=_snake_case       ,   )
								self.parent.assertEqual(result.prediction_logits.shape       ,   (self.batch_size, self.seq_length, self.vocab_size)	)
								self.parent.assertEqual(result.sop_logits.shape       ,   (self.batch_size, config.num_labels)	)




			def      lowerCamelCase__     (				self						:					List[Any]       ,   _snake_case						:					Optional[Any]       ,   _snake_case						:					Any       ,   _snake_case						:					str       ,   _snake_case						:					List[Any]       ,   _snake_case						:					Any       ,   _snake_case						:					Optional[Any]       ,   _snake_case						:					List[Any]	)      -> Optional[Any]:







								"""simple docstring"""
								A_				 =						AlbertForMaskedLM(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(_snake_case       ,   attention_mask=_snake_case       ,   token_type_ids=_snake_case       ,   labels=_snake_case	)
								self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.seq_length, self.vocab_size)	)




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







								"""simple docstring"""
								A_				 =						AlbertForQuestionAnswering(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(
								    _snake_case       ,   attention_mask=_snake_case       ,   token_type_ids=_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      lowerCamelCase__     (				self						:					Tuple       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					int       ,   _snake_case						:					int       ,   _snake_case						:					str       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					Tuple       ,   _snake_case						:					int	)      -> Dict:







								"""simple docstring"""
								A_				 =						self.num_labels
								A_				 =						AlbertForSequenceClassification(_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(_snake_case       ,   attention_mask=_snake_case       ,   token_type_ids=_snake_case       ,   labels=_snake_case	)
								self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.num_labels)	)




			def      lowerCamelCase__     (				self						:					Dict       ,   _snake_case						:					Tuple       ,   _snake_case						:					int       ,   _snake_case						:					Optional[int]       ,   _snake_case						:					Optional[int]       ,   _snake_case						:					List[Any]       ,   _snake_case						:					Optional[Any]       ,   _snake_case						:					Optional[int]	)      -> List[Any]:







								"""simple docstring"""
								A_				 =						self.num_labels
								A_				 =						AlbertForTokenClassification(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(_snake_case       ,   attention_mask=_snake_case       ,   token_type_ids=_snake_case       ,   labels=_snake_case	)
								self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.seq_length, self.num_labels)	)




			def      lowerCamelCase__     (				self						:					List[str]       ,   _snake_case						:					Optional[int]       ,   _snake_case						:					Tuple       ,   _snake_case						:					Any       ,   _snake_case						:					str       ,   _snake_case						:					Optional[Any]       ,   _snake_case						:					str       ,   _snake_case						:					List[Any]	)      -> List[Any]:







								"""simple docstring"""
								A_				 =						self.num_choices
								A_				 =						AlbertForMultipleChoice(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						input_ids.unsqueeze(1	).expand(-1       ,   self.num_choices       ,   -1	).contiguous()
								A_				 =						token_type_ids.unsqueeze(1	).expand(-1       ,   self.num_choices       ,   -1	).contiguous()
								A_				 =						input_mask.unsqueeze(1	).expand(-1       ,   self.num_choices       ,   -1	).contiguous()
								A_				 =						model(
								    _snake_case       ,   attention_mask=_snake_case       ,   token_type_ids=_snake_case       ,   labels=_snake_case       ,   )
								self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.num_choices)	)






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







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





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




			"""simple docstring"""







			snake_case	      =				(
			    (
			        AlbertModel,
			        AlbertForPreTraining,
			        AlbertForMaskedLM,
			        AlbertForMultipleChoice,
			        AlbertForSequenceClassification,
			        AlbertForTokenClassification,
			        AlbertForQuestionAnswering,
			    )
			    if is_torch_available()
			    else ()
			)
			snake_case	      =				(
			    {
			        "feature-extraction": AlbertModel,
			        "fill-mask": AlbertForMaskedLM,
			        "question-answering": AlbertForQuestionAnswering,
			        "text-classification": AlbertForSequenceClassification,
			        "token-classification": AlbertForTokenClassification,
			        "zero-shot": AlbertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			snake_case	      =				True




			def      lowerCamelCase__     (				self						:					str       ,   _snake_case						:					Tuple       ,   _snake_case						:					Any       ,   _snake_case						:					List[Any]=False	)      -> int:







								"""simple docstring"""
								A_				 =						super()._prepare_for_class(_snake_case       ,   _snake_case       ,   return_labels=_snake_case	)

								if return_labels:
													if model_class in get_values(_snake_case	):
																		A_				 =						torch.zeros(
																		    (self.model_tester.batch_size, self.model_tester.seq_length)       ,   dtype=torch.long       ,   device=_snake_case	)
																		A_				 =						torch.zeros(
																		    self.model_tester.batch_size       ,   dtype=torch.long       ,   device=_snake_case	)
								return inputs_dict




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







								"""simple docstring"""
								A_				 =						AlbertModelTester(self	)
								A_				 =						ConfigTester(self       ,   config_class=_snake_case       ,   hidden_size=37	)




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







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




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







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case	)




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







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_pretraining(*_snake_case	)




			def      lowerCamelCase__     (				self						:					int	)      -> Dict:







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*_snake_case	)




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







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_multiple_choice(*_snake_case	)




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







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*_snake_case	)




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







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*_snake_case	)




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







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
													A_				 =						type
													self.model_tester.create_and_check_model(*_snake_case	)






			@slow
			def      lowerCamelCase__     (				self						:					List[str]	)      -> Dict:







								"""simple docstring"""
								for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													A_				 =						AlbertModel.from_pretrained(_snake_case	)
													self.assertIsNotNone(_snake_case	)





@require_torch
class __lowerCAmelCase				(					unittest.TestCase      ):




			"""simple docstring"""







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







								"""simple docstring"""
								A_				 =						AlbertModel.from_pretrained("albert-base-v2"	)
								A_				 =						torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]	)
								A_				 =						torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]	)
								with torch.no_grad():
													A_				 =						model(_snake_case       ,   attention_mask=_snake_case	)[0]
								A_				 =						torch.Size((1, 11, 768)	)
								self.assertEqual(output.shape       ,   _snake_case	)
								A_				 =						torch.tensor(
								    [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]]	)

								self.assertTrue(torch.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]"	)




