




from __future__ import annotations

import unittest

from transformers import EsmConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import numpy
       import tensorflow as tf

       from transformers.models.esm.modeling_tf_esm import (
           TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFEsmForMaskedLM,
           TFEsmForSequenceClassification,
           TFEsmForTokenClassification,
           TFEsmModel,
       )




class 		UpperCamelCase__	:

    '''simple docstring'''



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







    def     _lowercase     (    self     )     ->      List[str]:
           lowerCamelCase   :      Optional[Any]			 =					ids_tensor([self.batch_size, self.seq_length]     ,  self.vocab_size     )

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

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

           lowerCamelCase   :      Union[str, Any]			 =					EsmConfig(
               vocab_size=self.vocab_size     ,  hidden_size=self.hidden_size     ,  num_hidden_layers=self.num_hidden_layers     ,  pad_token_id=1     ,  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     ,  )

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







    def     _lowercase     (    self     )     ->      Dict:
           (
               (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      
           )   :      Dict			 =					self.prepare_config_and_inputs()

           lowerCamelCase   :      Union[str, Any]			 =					True
           lowerCamelCase   :      int			 =					floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
           lowerCamelCase   :      int			 =					ids_tensor([self.batch_size, self.seq_length]     ,  vocab_size=2     )

           return (
               config,
               input_ids,
               input_mask,
               sequence_labels,
               token_labels,
               choice_labels,
               encoder_hidden_states,
               encoder_attention_mask,
           )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     )     ->      List[Any]:
           lowerCamelCase   :      List[Any]			 =					TFEsmModel(config=UpperCamelCase__     )
           lowerCamelCase   :      int			 =					{"input_ids": input_ids, "attention_mask": input_mask}
           lowerCamelCase   :      List[Any]			 =					model(UpperCamelCase__     )

           lowerCamelCase   :      int			 =					[input_ids, input_mask]
           lowerCamelCase   :      Optional[Any]			 =					model(UpperCamelCase__     )

           lowerCamelCase   :      Union[str, Any]			 =					model(UpperCamelCase__     )

           self.parent.assertEqual(result.last_hidden_state.shape     ,  (self.batch_size, self.seq_length, self.hidden_size)     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  )     ->      str:
           lowerCamelCase   :      Optional[int]			 =					True

           lowerCamelCase   :      Union[str, Any]			 =					TFEsmModel(config=UpperCamelCase__     )
           lowerCamelCase   :      str			 =					{
               "input_ids": input_ids,
               "attention_mask": input_mask,
               "encoder_hidden_states": encoder_hidden_states,
               "encoder_attention_mask": encoder_attention_mask,
           }
           lowerCamelCase   :      List[str]			 =					model(UpperCamelCase__     )

           lowerCamelCase   :      Tuple			 =					[input_ids, input_mask]
           lowerCamelCase   :      Dict			 =					model(UpperCamelCase__     ,  encoder_hidden_states=UpperCamelCase__     )

           # Also check the case where encoder outputs are not passed
           lowerCamelCase   :      Any			 =					model(UpperCamelCase__     ,  attention_mask=UpperCamelCase__     )

           self.parent.assertEqual(result.last_hidden_state.shape     ,  (self.batch_size, self.seq_length, self.hidden_size)     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     )     ->      int:
           lowerCamelCase   :      List[str]			 =					TFEsmForMaskedLM(config=UpperCamelCase__     )
           lowerCamelCase   :      Any			 =					model([input_ids, input_mask]     )
           self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.seq_length, self.vocab_size)     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__     )     ->      List[Any]:
           lowerCamelCase   :      List[Any]			 =					self.num_labels
           lowerCamelCase   :      Dict			 =					TFEsmForTokenClassification(config=UpperCamelCase__     )
           lowerCamelCase   :      List[str]			 =					{"input_ids": input_ids, "attention_mask": input_mask}
           lowerCamelCase   :      Dict			 =					model(UpperCamelCase__     )
           self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.seq_length, self.num_labels)     )







    def     _lowercase     (    self     )     ->      Optional[Any]:
           lowerCamelCase   :      Tuple			 =					self.prepare_config_and_inputs()
           (
               (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      (
               lowerCamelCase
           ) ,      
           )   :      Optional[Any]			 =					config_and_inputs
           lowerCamelCase   :      Any			 =					{"input_ids": input_ids, "attention_mask": input_mask}
           return config, inputs_dict




@require_tf
class 		UpperCamelCase__	(lowerCAmelCase__    ,				lowerCAmelCase__    ,				unittest.TestCase     ):

    '''simple docstring'''



    lowerCamelCase_      :	Dict	     =      (
        (
            TFEsmModel,
            TFEsmForMaskedLM,
            TFEsmForSequenceClassification,
            TFEsmForTokenClassification,
        )
        if is_tf_available()
        else ()
    )
    lowerCamelCase_      :	Optional[Any]	     =      (
        {
            """feature-extraction""": TFEsmModel,
            """fill-mask""": TFEsmForMaskedLM,
            """text-classification""": TFEsmForSequenceClassification,
            """token-classification""": TFEsmForTokenClassification,
            """zero-shot""": TFEsmForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    lowerCamelCase_      :	Any	     =      False
    lowerCamelCase_      :	Dict	     =      False







    def     _lowercase     (    self     )     ->      Any:
           lowerCamelCase   :      Tuple			 =					TFEsmModelTester(self     )
           lowerCamelCase   :      int			 =					ConfigTester(self     ,  config_class=UpperCamelCase__     ,  hidden_size=37     )







    def     _lowercase     (    self     )     ->      List[str]:
           self.config_tester.run_common_tests()







    def     _lowercase     (    self     )     ->      str:
           lowerCamelCase   :      Optional[int]			 =					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase__     )







    def     _lowercase     (    self     )     ->      List[str]:
           lowerCamelCase   :      Any			 =					self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_model_as_decoder(*UpperCamelCase__     )







    def     _lowercase     (    self     )     ->      Union[str, Any]:
           lowerCamelCase   :      Any			 =					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__     )







    def     _lowercase     (    self     )     ->      List[Any]:
           lowerCamelCase   :      Dict			 =					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__     )







    @slow
    def     _lowercase     (    self     )     ->      List[Any]:
           for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowerCamelCase   :      Any			 =					TFEsmModel.from_pretrained(UpperCamelCase__     )
                  self.assertIsNotNone(UpperCamelCase__     )







    @unittest.skip("Protein models do not support embedding resizing."     )
    def     _lowercase     (    self     )     ->      List[str]:
           pass







    @unittest.skip("Protein models do not support embedding resizing."     )
    def     _lowercase     (    self     )     ->      Optional[Any]:
           pass







    def     _lowercase     (    self     )     ->      Tuple:
           lowerCamelCase ,      lowerCamelCase   :      Dict			 =					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  lowerCamelCase   :      Optional[Any]			 =					model_class(UpperCamelCase__     )
                  assert isinstance(model.get_input_embeddings()     ,  tf.keras.layers.Layer     )
                  if model_class is TFEsmForMaskedLM:
                         # Output embedding test differs from the main test because they're a matrix, not a layer
                         lowerCamelCase   :      Any			 =					model.get_bias()
                         assert isinstance(UpperCamelCase__     ,  UpperCamelCase__     )
                         for k, v in name.items():
                                assert isinstance(UpperCamelCase__     ,  tf.Variable     )
                  else:
                         lowerCamelCase   :      str			 =					model.get_output_embeddings()
                         assert x is None
                         lowerCamelCase   :      Optional[Any]			 =					model.get_bias()
                         assert name is None




@require_tf
class 		UpperCamelCase__	(unittest.TestCase     ):

    '''simple docstring'''



    @slow
    def     _lowercase     (    self     )     ->      Dict:
           lowerCamelCase   :      int			 =					TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"     )

           lowerCamelCase   :      Union[str, Any]			 =					tf.constant([[0, 1, 2, 3, 4, 5]]     )
           lowerCamelCase   :      Optional[int]			 =					model(UpperCamelCase__     )[0]
           lowerCamelCase   :      Union[str, Any]			 =					[1, 6, 33]
           self.assertEqual(list(output.numpy().shape     )     ,  UpperCamelCase__     )
           # compare the actual values for a slice.
           lowerCamelCase   :      List[str]			 =					tf.constant(
               [
                   [
                       [8.921518, -10.589814, -6.4671307],
                       [-6.3967156, -13.911377, -1.1211915],
                       [-7.781247, -13.951557, -3.740592],
                   ]
               ]     )
           self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()     ,  expected_slice.numpy()     ,  atol=1e-2     )     )







    @slow
    def     _lowercase     (    self     )     ->      str:
           lowerCamelCase   :      Dict			 =					TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"     )

           lowerCamelCase   :      int			 =					tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]     )
           lowerCamelCase   :      Dict			 =					model(UpperCamelCase__     )[0]
           # compare the actual values for a slice.
           lowerCamelCase   :      int			 =					tf.constant(
               [
                   [
                       [0.14443092, 0.54125327, 0.3247739],
                       [0.30340484, 0.00526676, 0.31077722],
                       [0.32278043, -0.24987096, 0.3414628],
                   ]
               ]     )
           self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()     ,  expected_slice.numpy()     ,  atol=1e-4     )     )












import argparse

from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging


logging.set_verbosity_info()

def      A      (      _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )	-> Dict:
       # Initialise PyTorch model
       lowerCamelCase   :      Any			 =					TaConfig.from_json_file(_SCREAMING_SNAKE_CASE    )
       print(f'''Building PyTorch model from configuration: {config}'''    )
       lowerCamelCase   :      str			 =					TaForConditionalGeneration(_SCREAMING_SNAKE_CASE    )

       # Load weights from tf checkpoint
       load_tf_weights_in_ta(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE    )

       # Save pytorch-model
       print(f'''Save PyTorch model to {pytorch_dump_path}'''    )
       model.save_pretrained(_SCREAMING_SNAKE_CASE    )


if __name__ == "__main__":
       SCREAMING_SNAKE_CASE__       :      str  =   argparse.ArgumentParser()
       # Required parameters
       parser.add_argument(
           '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
       )
       parser.add_argument(
           '--config_file',
           default=None,
           type=str,
           required=True,
           help=(
               'The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.'
           ),
       )
       parser.add_argument(
           '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
       )
       SCREAMING_SNAKE_CASE__       :      str  =   parser.parse_args()
       convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)






