





from dataclasses import asdict, dataclass
from typing import Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase	:	Optional[int]		     =       logging.get_logger(__name__)

# TODO Update this
UpperCAmelCase	:	Optional[Any]		     =       {
    """facebook/esm-1b""": """https://huggingface.co/facebook/esm-1b/resolve/main/config.json""",
    # See all ESM models at https://huggingface.co/models?filter=esm
}







class 				__lowerCAmelCase       (    UpperCamelCase__):
      _lowercase				:					List[Any]						=			"""esm"""







      def __init__(    self		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=7_6_8		,      lowerCAmelCase__=1_2		,      lowerCAmelCase__=1_2		,      lowerCAmelCase__=3_0_7_2		,      lowerCAmelCase__=0.1		,      lowerCAmelCase__=0.1		,      lowerCAmelCase__=1_0_2_6		,      lowerCAmelCase__=0.02		,      lowerCAmelCase__=1E-12		,      lowerCAmelCase__="absolute"		,      lowerCAmelCase__=True		,      lowerCAmelCase__=None		,      lowerCAmelCase__=False		,      lowerCAmelCase__=False		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      **lowerCAmelCase__		,      )   ->						List[Any]:



        '''simple docstring'''




        super().__init__(pad_token_id=lowerCAmelCase__		,      mask_token_id=lowerCAmelCase__		,      **lowerCAmelCase__							)

        a__	:					Union[str, Any]										=vocab_size
        a__	:					List[Any]										=hidden_size
        a__	:					Optional[Any]										=num_hidden_layers
        a__	:					str										=num_attention_heads
        a__	:					Tuple										=intermediate_size
        a__	:					List[Any]										=hidden_dropout_prob
        a__	:					Optional[int]										=attention_probs_dropout_prob
        a__	:					int										=max_position_embeddings
        a__	:					List[str]										=initializer_range
        a__	:					Optional[int]										=layer_norm_eps
        a__	:					Dict										=position_embedding_type
        a__	:					int										=use_cache
        a__	:					Tuple										=emb_layer_norm_before
        a__	:					Union[str, Any]										=token_dropout
        a__	:					List[Any]										=is_folding_model
        if is_folding_model:
          if esmfold_config is None:
            logger.info("No esmfold_config supplied for folding model, using default values."							)
            a__	:					List[Any]										=EsmFoldConfig()
          elif isinstance(lowerCAmelCase__		,      lowerCAmelCase__							):
            a__	:					Any										=EsmFoldConfig(**lowerCAmelCase__							)
          a__	:					Any										=esmfold_config
          if vocab_list is None:
            logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!"							)
            a__	:					List[Any]										=get_default_vocab_list()
          else:
            a__	:					List[str]										=vocab_list
        else:
          a__	:					Any										=None
          a__	:					str										=None
        if self.esmfold_config is not None and getattr(self.esmfold_config		,      "use_esm_attn_map"		,      lowerCAmelCase__							):
          raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!"							)







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



        '''simple docstring'''




        a__	:					Optional[Any]										=super().to_dict()
        if isinstance(self.esmfold_config		,      lowerCAmelCase__							):
          a__	:					List[str]										=self.esmfold_config.to_dict()
        return output







@dataclass
class 				__lowerCAmelCase       :
      _lowercase				:					str						=			None
      _lowercase				:					bool						=			True
      _lowercase				:					bool						=			False
      _lowercase				:					bool						=			False
      _lowercase				:					bool						=			False
      _lowercase				:					float						=			0

      _lowercase				:					bool						=			True
      _lowercase				:					bool						=			False

      _lowercase				:					int						=			128
      _lowercase				:					"TrunkConfig"						=			None







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



        '''simple docstring'''




        if self.trunk is None:
          a__	:					List[Any]										=TrunkConfig()
        elif isinstance(self.trunk		,      lowerCAmelCase__							):
          a__	:					Dict										=TrunkConfig(**self.trunk							)







      def    _lowercase  (    self							)   ->						Dict:



        '''simple docstring'''




        a__	:					Any										=asdict(self							)
        a__	:					List[str]										=self.trunk.to_dict()
        return output







@dataclass
class 				__lowerCAmelCase       :
      _lowercase				:					int						=			48
      _lowercase				:					int						=			1024
      _lowercase				:					int						=			128
      _lowercase				:					int						=			32
      _lowercase				:					int						=			32
      _lowercase				:					int						=			32
      _lowercase				:					float						=			0
      _lowercase				:					float						=			0
      _lowercase				:					bool						=			False
      _lowercase				:					int						=			4
      _lowercase				:					Optional[int]						=			128
      _lowercase				:					"StructureModuleConfig"						=			None







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        if self.structure_module is None:
          a__	:					List[Any]										=StructureModuleConfig()
        elif isinstance(self.structure_module		,      lowerCAmelCase__							):
          a__	:					Dict										=StructureModuleConfig(**self.structure_module							)

        if self.max_recycles <= 0:
          raise ValueError(F'''`max_recycles` should be positive, got {self.max_recycles}.'''							)
        if self.sequence_state_dim % self.sequence_state_dim != 0:
          raise ValueError(
              "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
              F''' {self.sequence_state_dim} and {self.sequence_state_dim}.'''							)
        if self.pairwise_state_dim % self.pairwise_state_dim != 0:
          raise ValueError(
              "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
              F''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.'''							)

        a__	:					int										=self.sequence_state_dim // self.sequence_head_width
        a__	:					Dict										=self.pairwise_state_dim // self.pairwise_head_width

        if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
          raise ValueError(
              "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
              F''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.'''							)
        if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
          raise ValueError(
              "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
              F''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.'''							)
        if self.pairwise_state_dim % 2 != 0:
          raise ValueError(F'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.'''							)

        if self.dropout >= 0.4:
          raise ValueError(F'''`dropout` should not be greater than 0.4, got {self.dropout}.'''							)







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        a__	:					str										=asdict(self							)
        a__	:					List[str]										=self.structure_module.to_dict()
        return output







@dataclass
class 				__lowerCAmelCase       :
      _lowercase				:					int						=			384
      _lowercase				:					int						=			128
      _lowercase				:					int						=			16
      _lowercase				:					int						=			128
      _lowercase				:					int						=			12
      _lowercase				:					int						=			4
      _lowercase				:					int						=			8
      _lowercase				:					float						=			0.1
      _lowercase				:					int						=			8
      _lowercase				:					int						=			1
      _lowercase				:					int						=			2
      _lowercase				:					int						=			7
      _lowercase				:					int						=			10
      _lowercase				:					float						=			1E-8
      _lowercase				:					float						=			1E5







      def    _lowercase  (    self							)   ->						Tuple:



        '''simple docstring'''




        return asdict(self							)
def      _A       (		):





  """simple docstring"""



  return (
      "<cls>",
      "<pad>",
      "<eos>",
      "<unk>",
      "L",
      "A",
      "G",
      "V",
      "S",
      "E",
      "R",
      "T",
      "I",
      "D",
      "P",
      "K",
      "Q",
      "N",
      "F",
      "Y",
      "M",
      "H",
      "W",
      "C",
      "X",
      "B",
      "U",
      "Z",
      "O",
      ".",
      "-",
      "<null_1>",
      "<mask>",
  )













import argparse
import os

import torch

from transformers import (
    XLNetConfig,
    XLNetForQuestionAnswering,
    XLNetForSequenceClassification,
    XLNetLMHeadModel,
    load_tf_weights_in_xlnet,
)
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


UpperCAmelCase	:	int		     =       {
    """cola""": 2,
    """mnli""": 3,
    """mrpc""": 2,
    """sst-2""": 2,
    """sts-b""": 1,
    """qqp""": 2,
    """qnli""": 2,
    """rte""": 2,
    """wnli""": 2,
}


logging.set_verbosity_info()
def      _A       (		SCREAMING_SNAKE_CASE     :   List[Any]       ,       SCREAMING_SNAKE_CASE     :   Dict       ,       SCREAMING_SNAKE_CASE     :   Dict       ,       SCREAMING_SNAKE_CASE     :   Union[str, Any]=None						):





  """simple docstring"""



  a__	:					Optional[int]										=XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE						)

  a__	:					Dict										=finetuning_task.lower() if finetuning_task is not None else ""
  if finetuning_task in GLUE_TASKS_NUM_LABELS:
    print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}'''						)
    a__	:					List[str]										=finetuning_task
    a__	:					Tuple										=GLUE_TASKS_NUM_LABELS[finetuning_task]
    a__	:					List[Any]										=XLNetForSequenceClassification(SCREAMING_SNAKE_CASE						)
  elif "squad" in finetuning_task:
    a__	:					Optional[int]										=finetuning_task
    a__	:					Dict										=XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE						)
  else:
    a__	:					List[Any]										=XLNetLMHeadModel(SCREAMING_SNAKE_CASE						)

  # Load weights from tf checkpoint
  load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						)

  # Save pytorch-model
  a__	:					Dict										=os.path.join(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						)
  a__	:					Dict										=os.path.join(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						)
  print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE						)}'''						)
  torch.save(model.state_dict()       ,       SCREAMING_SNAKE_CASE						)
  print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE						)}'''						)
  with open(SCREAMING_SNAKE_CASE       ,       "w"       ,       encoding="utf-8"						) as f:
    f.write(config.to_json_string()						)


if __name__ == "__main__":
     UpperCAmelCase	:	List[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(
         """--xlnet_config_file""",
         default=None,
         type=str,
         required=True,
         help=(
             """The config json file corresponding to the pre-trained XLNet model. \n"""
             """This specifies the model architecture."""
         ),
     )
     parser.add_argument(
         """--pytorch_dump_folder_path""",
         default=None,
         type=str,
         required=True,
         help="""Path to the folder to store the PyTorch model or dataset/vocab.""",
     )
     parser.add_argument(
         """--finetuning_task""",
         default=None,
         type=str,
         help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""",
     )
     UpperCAmelCase	:	int		     =       parser.parse_args()
     print(args)

     convert_xlnet_checkpoint_to_pytorch(
         args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task
     )






