


'''simple docstring'''







import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
    datefmt='%m/%d/%Y %H:%M:%S',
    level=logging.INFO,
)
a__    :   Dict								=			logging.getLogger(__name__)

a__    :   int								=			int(1_0_0_0_0)  # Hardcoded max length to avoid infinite loop

a__    :   int								=			{
    'gpt2': (GPTaLMHeadModel, GPTaTokenizer),
    'ctrl': (CTRLLMHeadModel, CTRLTokenizer),
    'openai-gpt': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    'xlnet': (XLNetLMHeadModel, XLNetTokenizer),
    'transfo-xl': (TransfoXLLMHeadModel, TransfoXLTokenizer),
    'xlm': (XLMWithLMHeadModel, XLMTokenizer),
    'gptj': (GPTJForCausalLM, AutoTokenizer),
    'bloom': (BloomForCausalLM, BloomTokenizerFast),
    'llama': (LlamaForCausalLM, LlamaTokenizer),
    'opt': (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
a__    :   List[Any]								=			'In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>'







def _UpperCamelCase			(	__A       )				->						str:


      '''simple docstring'''



      np.random.seed(args.seed       )
      torch.manual_seed(args.seed       )
      if args.n_gpu > 0:
            torch.cuda.manual_seed_all(args.seed       )







def _UpperCamelCase			(	__A ,     __A ,     __A ,     __A       )				->						int:


      '''simple docstring'''



      if args.temperature > 0.7:
            logger.info("CTRL typically works better with lower temperatures (and lower top_k)."       )

      UpperCamelCase__      =							tokenizer.encode(__A ,     add_special_tokens=__A       )
      if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()       ):
            logger.info("WARNING! You are not starting your generation from a control code so you won't get good results"       )
      return prompt_text







def _UpperCamelCase			(	__A ,     __A ,     __A ,     __A       )				->						List[Any]:


      '''simple docstring'''



      UpperCamelCase__      =							hasattr(model.config ,     "use_lang_emb"       ) and model.config.use_lang_emb
      if hasattr(model.config ,     "lang2id"       ) and use_lang_emb:
            UpperCamelCase__      =							model.config.langaid.keys()
            if args.xlm_language in available_languages:
                  UpperCamelCase__      =							args.xlm_language
            else:
                  UpperCamelCase__      =							None
                  while language not in available_languages:
                        UpperCamelCase__      =							input("Using XLM. Select language in " + str(list(__A       )       ) + " >>> "       )

            UpperCamelCase__      =							model.config.langaid[language]
            # kwargs["language"] = tokenizer.lang2id[language]

      # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
      # XLM masked-language modeling (MLM) models need masked token
      # is_xlm_mlm = "mlm" in args.model_name_or_path
      # if is_xlm_mlm:
      #     kwargs["mask_token_id"] = tokenizer.mask_token_id

      return prompt_text







def _UpperCamelCase			(	__A ,     __A ,     __A ,     __A       )				->						List[Any]:


      '''simple docstring'''



      UpperCamelCase__      =							args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
      UpperCamelCase__      =							prefix + prompt_text
      return prompt_text







def _UpperCamelCase			(	__A ,     __A ,     __A ,     __A       )				->						List[str]:


      '''simple docstring'''



      UpperCamelCase__      =							args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
      UpperCamelCase__      =							prefix + prompt_text
      return prompt_text


a__    :   Tuple								=			{
    'ctrl': prepare_ctrl_input,
    'xlm': prepare_xlm_input,
    'xlnet': prepare_xlnet_input,
    'transfo-xl': prepare_transfoxl_input,
}







def _UpperCamelCase			(	__A ,     __A       )				->						Any:


      '''simple docstring'''



      if length < 0 and max_sequence_length > 0:
            UpperCamelCase__      =							max_sequence_length
      elif 0 < max_sequence_length < length:
            UpperCamelCase__      =							max_sequence_length  # No generation bigger than model size
      elif length < 0:
            UpperCamelCase__      =							MAX_LENGTH  # avoid infinite loop
      return length







def _UpperCamelCase			(	__A       )				->						List[Any]:


      '''simple docstring'''



      UpperCamelCase__      =							None
      if hasattr(__A ,     "hidden_size"       ):
            UpperCamelCase__      =							model_config.hidden_size
      elif hasattr(__A ,     "n_embed"       ):
            UpperCamelCase__      =							model_config.n_embed
      elif hasattr(__A ,     "n_embd"       ):
            UpperCamelCase__      =							model_config.n_embd

      UpperCamelCase__      =							None
      if hasattr(__A ,     "num_attention_heads"       ):
            UpperCamelCase__      =							model_config.num_attention_heads
      elif hasattr(__A ,     "n_head"       ):
            UpperCamelCase__      =							model_config.n_head

      if embedding_size is None or num_head is None or num_head == 0:
            raise ValueError("Check the model config"       )

      UpperCamelCase__      =							int(embedding_size / num_head       )
      if hasattr(__A ,     "n_layer"       ):
            UpperCamelCase__      =							model_config.n_layer
      elif hasattr(__A ,     "num_hidden_layers"       ):
            UpperCamelCase__      =							model_config.num_hidden_layers
      else:
            raise ValueError("Number of hidden layers couldn't be determined from the model config"       )

      return num_layer, num_head, num_embedding_size_per_head







def _UpperCamelCase			(	__A ,     __A ,     __A       )				->						int:


      '''simple docstring'''



      UpperCamelCase__   ,      UpperCamelCase__   ,      UpperCamelCase__      =							sparse_model_config(model.config       )
      if model.config.model_type == "bloom":
            UpperCamelCase__      =							tuple(
                (
                    torch.empty(int(num_attention_heads * batch_size       ) ,     __A ,     __A       )
                    .to(model.dtype       )
                    .to(model.device       ),
                    torch.empty(int(num_attention_heads * batch_size       ) ,     __A ,     __A       )
                    .to(model.dtype       )
                    .to(model.device       ),
                )
                for _ in range(__A       )       )
      else:
            UpperCamelCase__      =							tuple(
                (
                    torch.empty(__A ,     __A ,     __A ,     __A       )
                    .to(model.dtype       )
                    .to(model.device       ),
                    torch.empty(__A ,     __A ,     __A ,     __A       )
                    .to(model.dtype       )
                    .to(model.device       ),
                )
                for _ in range(__A       )       )
      return past_key_values







def _UpperCamelCase			(	__A ,     __A ,     __A       )				->						int:


      '''simple docstring'''



      UpperCamelCase__      =							len(__A       )
      UpperCamelCase__      =							tokenizer.batch_encode_plus(__A ,     return_tensors="pt"       )
      UpperCamelCase__      =							dummy_input.to(model.device       )
      if model.config.use_cache:
            UpperCamelCase__      =							generate_past_key_values(__A ,     __A ,     1       )
      UpperCamelCase__      =							torch.cat(
          [
              torch.zeros(dummy_input["attention_mask"].shape[0] ,     1       )
              .to(dummy_input["attention_mask"].dtype       )
              .to(model.device       ),
              dummy_input["attention_mask"],
          ] ,     -1 ,     )
      return dummy_input
class    lowercase_	(       a__  ):
    __UpperCAmelCase       =      ('_optimized', '_default')


    def __init__(	self    ,   a    ,   a       ):
          UpperCamelCase__      =							optimized
          UpperCamelCase__      =							default


    def __call__(	self    ,   *a    ,   **a       ):
          if kwargs["past_key_values"] is None and self._default.config.use_cache:
                UpperCamelCase__      =							generate_past_key_values(self._default    ,   kwargs["input_ids"].shape[0]    ,   0       )
          kwargs.pop("position_ids"    ,   a       )
          for k in list(kwargs.keys()       ):
                if kwargs[k] is None or isinstance(kwargs[k]    ,   a       ):
                      kwargs.pop(a       )
          UpperCamelCase__      =							self._optimized(**a       )
          UpperCamelCase__      =							outputs[0]
          UpperCamelCase__      =							outputs[1]
          UpperCamelCase__      =							CausalLMOutputWithPast(
              loss=a    ,   logits=a    ,   past_key_values=a    ,   hidden_states=a    ,   attentions=a    ,   )
          return fixed_output


    def __getattr__(	self    ,   a       ):
          return getattr(self._default    ,   a       )


    def   __a				(	self    ,   a    ,   a=None    ,   a=None    ,   a=None    ,   **a       ):
          return self._default.prepare_inputs_for_generation(
              a    ,   past_key_values=a    ,   inputs_embeds=a    ,   use_cache=a    ,   **a       )


    def   __a				(	self    ,   a    ,   a       ):
          return self._default._reorder_cache(a    ,   a       )







def _UpperCamelCase			(	)				->						Dict:


      '''simple docstring'''



      UpperCamelCase__      =							argparse.ArgumentParser()
      parser.add_argument(
          "--model_type" ,     default=__A ,     type=__A ,     required=__A ,     help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()       ) ,     )
      parser.add_argument(
          "--model_name_or_path" ,     default=__A ,     type=__A ,     required=__A ,     help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(MODEL_CLASSES.keys()       ) ,     )

      parser.add_argument("--prompt" ,     type=__A ,     default=""       )
      parser.add_argument("--length" ,     type=__A ,     default=20       )
      parser.add_argument("--stop_token" ,     type=__A ,     default=__A ,     help="Token at which text generation is stopped"       )

      parser.add_argument(
          "--temperature" ,     type=__A ,     default=1.0 ,     help="temperature of 1.0 has no effect, lower tend toward greedy sampling" ,     )
      parser.add_argument(
          "--repetition_penalty" ,     type=__A ,     default=1.0 ,     help="primarily useful for CTRL model; in that case, use 1.2"       )
      parser.add_argument("--k" ,     type=__A ,     default=0       )
      parser.add_argument("--p" ,     type=__A ,     default=0.9       )

      parser.add_argument("--prefix" ,     type=__A ,     default="" ,     help="Text added prior to input."       )
      parser.add_argument("--padding_text" ,     type=__A ,     default="" ,     help="Deprecated, the use of `--prefix` is preferred."       )
      parser.add_argument("--xlm_language" ,     type=__A ,     default="" ,     help="Optional language when used with the XLM model."       )

      parser.add_argument("--seed" ,     type=__A ,     default=42 ,     help="random seed for initialization"       )
      parser.add_argument("--no_cuda" ,     action="store_true" ,     help="Avoid using CUDA when available"       )
      parser.add_argument("--num_return_sequences" ,     type=__A ,     default=1 ,     help="The number of samples to generate."       )
      parser.add_argument(
          "--fp16" ,     action="store_true" ,     help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" ,     )
      parser.add_argument("--jit" ,     action="store_true" ,     help="Whether or not to use jit trace to accelerate inference"       )
      UpperCamelCase__      =							parser.parse_args()

      UpperCamelCase__      =							torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"       )
      UpperCamelCase__      =							0 if args.no_cuda else torch.cuda.device_count()

      logger.warning(F'''device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'''       )

      set_seed(__A       )

      # Initialize the model and tokenizer
      try:
            UpperCamelCase__      =							args.model_type.lower()
            UpperCamelCase__   ,      UpperCamelCase__      =							MODEL_CLASSES[args.model_type]
      except KeyError:
            raise KeyError("the model {} you specified is not supported. You are welcome to add it and open a PR :)"       )

      UpperCamelCase__      =							tokenizer_class.from_pretrained(args.model_name_or_path       )
      if tokenizer.pad_token is None:
            UpperCamelCase__      =							tokenizer.eos_token
      UpperCamelCase__      =							model_class.from_pretrained(args.model_name_or_path       )
      model.to(args.device       )

      if args.fpaa:
            model.half()
      UpperCamelCase__      =							getattr(model.config ,     "max_position_embeddings" ,     0       )
      UpperCamelCase__      =							adjust_length_to_model(args.length ,     max_sequence_length=__A       )
      logger.info(__A       )

      UpperCamelCase__      =							args.prompt if args.prompt else input("Model prompt >>> "       )

      # Different models need different input formatting and/or extra arguments
      UpperCamelCase__      =							args.model_type in PREPROCESSING_FUNCTIONS.keys()
      if requires_preprocessing:
            UpperCamelCase__      =							PREPROCESSING_FUNCTIONS.get(args.model_type       )
            UpperCamelCase__      =							prepare_input(__A ,     __A ,     __A ,     __A       )

            if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
                  UpperCamelCase__      =							{"add_space_before_punct_symbol": True}
            else:
                  UpperCamelCase__      =							{}

            UpperCamelCase__      =							tokenizer.encode(
                __A ,     add_special_tokens=__A ,     return_tensors="pt" ,     **__A       )
      else:
            UpperCamelCase__      =							args.prefix if args.prefix else args.padding_text
            UpperCamelCase__      =							tokenizer.encode(prefix + prompt_text ,     add_special_tokens=__A ,     return_tensors="pt"       )
      UpperCamelCase__      =							encoded_prompt.to(args.device       )

      if encoded_prompt.size()[-1] == 0:
            UpperCamelCase__      =							None
      else:
            UpperCamelCase__      =							encoded_prompt

      if args.jit:
            UpperCamelCase__      =							["enable jit"]
            UpperCamelCase__      =							prepare_jit_inputs(__A ,     __A ,     __A       )
            torch._C._jit_set_texpr_fuser_enabled(__A       )
            UpperCamelCase__      =							False
            if hasattr(__A ,     "forward"       ):
                  UpperCamelCase__      =							inspect.signature(model.forward       )
            else:
                  UpperCamelCase__      =							inspect.signature(model.__call__       )
            UpperCamelCase__      =							tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(__A ,     __A       ) is not None       )
            UpperCamelCase__      =							torch.jit.trace(__A ,     __A ,     strict=__A       )
            UpperCamelCase__      =							torch.jit.freeze(traced_model.eval()       )
            traced_model(*__A       )
            traced_model(*__A       )

            UpperCamelCase__      =							_ModelFallbackWrapper(__A ,     __A       )

      UpperCamelCase__      =							model.generate(
          input_ids=__A ,     max_length=args.length + len(encoded_prompt[0]       ) ,     temperature=args.temperature ,     top_k=args.k ,     top_p=args.p ,     repetition_penalty=args.repetition_penalty ,     do_sample=__A ,     num_return_sequences=args.num_return_sequences ,     )

      # Remove the batch dimension when returning multiple sequences
      if len(output_sequences.shape       ) > 2:
            output_sequences.squeeze_()

      UpperCamelCase__      =							[]

      for generated_sequence_idx, generated_sequence in enumerate(__A       ):
            print(F'''=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='''       )
            UpperCamelCase__      =							generated_sequence.tolist()

            # Decode text
            UpperCamelCase__      =							tokenizer.decode(__A ,     clean_up_tokenization_spaces=__A       )

            # Remove all text after the stop token
            UpperCamelCase__      =							text[: text.find(args.stop_token       ) if args.stop_token else None]

            # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
            UpperCamelCase__      =							(
                prompt_text + text[len(tokenizer.decode(encoded_prompt[0] ,     clean_up_tokenization_spaces=__A       )       ) :]
            )

            generated_sequences.append(__A       )
            print(__A       )

      return generated_sequences


if __name__ == "__main__":
  main()









'''simple docstring'''







import argparse
import pathlib
from pathlib import Path
from tempfile import TemporaryDirectory

import esm as esm_module
import torch
from esm.esmfold.va.misc import batch_encode_sequences as esmfold_encode_sequences
from esm.esmfold.va.pretrained import esmfold_va

from transformers.models.esm.configuration_esm import EsmConfig, EsmFoldConfig
from transformers.models.esm.modeling_esm import (
    EsmForMaskedLM,
    EsmForSequenceClassification,
    EsmIntermediate,
    EsmLayer,
    EsmOutput,
    EsmSelfAttention,
    EsmSelfOutput,
)
from transformers.models.esm.modeling_esmfold import EsmForProteinFolding
from transformers.models.esm.tokenization_esm import EsmTokenizer
from transformers.utils import logging


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

a__    :   Optional[int]								=			[
    (
        'protein1',
        'MNGTEGPNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQHKKLRTPLNYILLNLAVADLFMVLGGFTSTLYTSLHGYFVFGPTGCNLEGFFATLGGEIALWSLVVLAIERYVVVCKPMSNFRFGENHAIMGVAFTWVMALACAAPPLAGWSRYIPEGLQCSCGIDYYTLKPEVNNESFVIYMFVVHFTIPMIIIFFCYGQLVFTVKEAAAQQQESATTQKAEKEVTRMVIIMVIAFLICWVPYASVAFYIFTHQGSNFGPIFMTIPAFFAKSAAIYNPVIYIMMNKQFRNCMLTTICCGKNPLGDDEASATVSKTETSQVAPA',
    ),
    ('protein2', 'MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLA'),
    ('protein3', 'MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLAGG'),
    ('protein4', 'MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLA'),
]

a__    :   Optional[int]								=			{
    'esm1b_t33_650M_UR50S': esm_module.pretrained.esm1b_t33_650M_UR50S,
    'esm1v_t33_650M_UR90S_1': esm_module.pretrained.esm1v_t33_650M_UR90S_1,
    'esm1v_t33_650M_UR90S_2': esm_module.pretrained.esm1v_t33_650M_UR90S_2,
    'esm1v_t33_650M_UR90S_3': esm_module.pretrained.esm1v_t33_650M_UR90S_3,
    'esm1v_t33_650M_UR90S_4': esm_module.pretrained.esm1v_t33_650M_UR90S_4,
    'esm1v_t33_650M_UR90S_5': esm_module.pretrained.esm1v_t33_650M_UR90S_5,
    'esm2_t48_15B_UR50D': esm_module.pretrained.esm2_t48_15B_UR50D,
    'esm2_t36_3B_UR50D': esm_module.pretrained.esm2_t36_3B_UR50D,
    'esm2_t33_650M_UR50D': esm_module.pretrained.esm2_t33_650M_UR50D,
    'esm2_t30_150M_UR50D': esm_module.pretrained.esm2_t30_150M_UR50D,
    'esm2_t12_35M_UR50D': esm_module.pretrained.esm2_t12_35M_UR50D,
    'esm2_t6_8M_UR50D': esm_module.pretrained.esm2_t6_8M_UR50D,
    'esmfold_v1': esmfold_va,
}

a__    :   List[Any]								=			list('ARNDCQEGHILKMFPSTWYV')

a__    :   Any								=			restypes + ['X']
a__    :   List[str]								=			restypes_with_x + ['<pad>', '<mask>', '<cls>', '<sep>', '<eos>']







def _UpperCamelCase			(	)				->						str:


      '''simple docstring'''



      with TemporaryDirectory() as tempdir:
            UpperCamelCase__      =							"\n".join(__A       )
            UpperCamelCase__      =							Path(__A       ) / "vocab.txt"
            vocab_file.write_text(__A       )
            UpperCamelCase__      =							EsmTokenizer(vocab_file=str(__A       )       )
      UpperCamelCase__      =							0  # Overlaps with 'A' but that seems to be what they want
      return hf_tokenizer







def _UpperCamelCase			(	__A ,     __A       )				->						List[str]:


      '''simple docstring'''



      UpperCamelCase__      =							our_module.load_state_dict(original_module.state_dict()       )
      if status.missing_keys:
            raise ValueError(F'''Missing keys: {status.missing_keys}'''       )
      if status.unexpected_keys:
            raise ValueError(F'''Unexpected keys: {status.unexpected_keys}'''       )







def _UpperCamelCase			(	__A ,     __A ,     __A ,     __A ,     __A       )				->						int:


      '''simple docstring'''



      if model.startswith("esmfold"       ):
            UpperCamelCase__      =							MODEL_MAPPING[model]()
      else:
            UpperCamelCase__   ,      UpperCamelCase__      =							MODEL_MAPPING[model]()
      esm.eval()  # disable dropout

      if model.startswith("esmfold"       ):
            UpperCamelCase__      =							esm.esm.embed_dim
            UpperCamelCase__      =							esm.esm.num_layers
            UpperCamelCase__      =							esm.esm.attention_heads
            UpperCamelCase__      =							4 * embed_dim
            UpperCamelCase__      =							esm.esm.token_dropout
            UpperCamelCase__      =							False  # This code path does not exist in ESM-2
            UpperCamelCase__      =							"rotary"
            UpperCamelCase__      =							True
            UpperCamelCase__      =							EsmFoldConfig()
            for key, val in esm.cfg.items():
                  if hasattr(__A ,     __A       ) and key != "trunk":
                        setattr(__A ,     __A ,     __A       )
            for key, val in esm.cfg.trunk.items():
                  if hasattr(esmfold_config.trunk ,     __A       ) and key != "structure_module":
                        setattr(esmfold_config.trunk ,     __A ,     __A       )
            for key, val in esm.cfg.trunk.structure_module.items():
                  if hasattr(esmfold_config.trunk.structure_module ,     __A       ):
                        setattr(esmfold_config.trunk.structure_module ,     __A ,     __A       )
      elif hasattr(__A ,     "args"       ):
            # Indicates an ESM-1b or ESM-1v model
            UpperCamelCase__      =							esm.args.embed_dim
            UpperCamelCase__      =							esm.args.layers
            UpperCamelCase__      =							esm.args.attention_heads
            UpperCamelCase__      =							esm.args.ffn_embed_dim
            UpperCamelCase__      =							esm.args.token_dropout
            UpperCamelCase__      =							True if esm.emb_layer_norm_before else False
            UpperCamelCase__      =							"absolute"
            UpperCamelCase__      =							False
            UpperCamelCase__      =							None
      else:
            # Indicates an ESM-2 model
            UpperCamelCase__      =							esm.embed_dim
            UpperCamelCase__      =							esm.num_layers
            UpperCamelCase__      =							esm.attention_heads
            UpperCamelCase__      =							4 * embed_dim  # This is hardcoded in ESM-2
            UpperCamelCase__      =							esm.token_dropout
            UpperCamelCase__      =							False  # This code path does not exist in ESM-2
            UpperCamelCase__      =							"rotary"
            UpperCamelCase__      =							False
            UpperCamelCase__      =							None

      if is_folding_model:
            UpperCamelCase__      =							esm.esm.alphabet
      UpperCamelCase__      =							tuple(alphabet.all_toks       )
      UpperCamelCase__      =							alphabet.mask_idx
      UpperCamelCase__      =							alphabet.padding_idx

      if is_folding_model:
            UpperCamelCase__      =							esm.esm
      else:
            UpperCamelCase__      =							esm

      UpperCamelCase__      =							EsmConfig(
          vocab_size=original_esm_model.embed_tokens.num_embeddings ,     mask_token_id=__A ,     hidden_size=__A ,     num_hidden_layers=__A ,     num_attention_heads=__A ,     intermediate_size=__A ,     max_position_embeddings=1026 ,     layer_norm_eps=1E-5 ,     attention_probs_dropout_prob=0.0 ,     hidden_dropout_prob=0.0 ,     pad_token_id=__A ,     emb_layer_norm_before=__A ,     token_dropout=__A ,     position_embedding_type=__A ,     is_folding_model=__A ,     esmfold_config=__A ,     vocab_list=__A ,     )
      if classification_head:
            UpperCamelCase__      =							esm.classification_heads["mnli"].out_proj.weight.shape[0]
      print("Our ESM config:" ,     __A       )

      if model.startswith("esmfold"       ):
            UpperCamelCase__      =							EsmForProteinFolding
      elif classification_head:
            UpperCamelCase__      =							EsmForSequenceClassification
      else:
            UpperCamelCase__      =							EsmForMaskedLM
      UpperCamelCase__      =							model_class(__A       )
      model.eval()

      # Now let's copy all the weights.
      # Embeddings
      UpperCamelCase__      =							original_esm_model.embed_tokens.weight
      if position_embedding_type == "absolute":
            UpperCamelCase__      =							original_esm_model.embed_positions.weight

      if config.emb_layer_norm_before:
            UpperCamelCase__      =							original_esm_model.emb_layer_norm_before.weight
            UpperCamelCase__      =							original_esm_model.emb_layer_norm_before.bias

      UpperCamelCase__      =							original_esm_model.emb_layer_norm_after.weight
      UpperCamelCase__      =							original_esm_model.emb_layer_norm_after.bias

      for i in range(config.num_hidden_layers       ):
            # Encoder: start of layer
            UpperCamelCase__      =							model.esm.encoder.layer[i]
            # esm_layer: TransformerSentenceEncoderLayer = original_esm_model.layers[i]
            UpperCamelCase__      =							original_esm_model.layers[i]

            # self attention
            UpperCamelCase__      =							layer.attention.self
            assert (
                esm_layer.self_attn.k_proj.weight.data.shape
                == esm_layer.self_attn.q_proj.weight.data.shape
                == esm_layer.self_attn.v_proj.weight.data.shape
                == torch.Size((config.hidden_size, config.hidden_size)       )
            )

            UpperCamelCase__      =							esm_layer.self_attn.q_proj.weight
            UpperCamelCase__      =							esm_layer.self_attn.q_proj.bias
            UpperCamelCase__      =							esm_layer.self_attn.k_proj.weight
            UpperCamelCase__      =							esm_layer.self_attn.k_proj.bias
            UpperCamelCase__      =							esm_layer.self_attn.v_proj.weight
            UpperCamelCase__      =							esm_layer.self_attn.v_proj.bias

            if getattr(esm_layer.self_attn ,     "rot_emb" ,     __A       ) is not None:
                  # Matt: Although inv_freq is not a trainable weight, it is computed at model init and cached.
                  # During the training of ESM-2 the model was converted to float16 precision, which also converts
                  # the inv_freq tensor, and the loss of precision remains even if the model is loaded later as float32.
                  # If we recompute inv_freq without this loss of precision then we will get subtly different rotary
                  # embeddings, which are enough to cause significant discrepancies in model outputs. To avoid this,
                  # we make sure the new model copies the data from the old inv_freq.
                  UpperCamelCase__      =							esm_layer.self_attn.rot_emb.inv_freq

            # LayerNorm changes for pre-activation
            UpperCamelCase__      =							esm_layer.self_attn_layer_norm.weight
            UpperCamelCase__      =							esm_layer.self_attn_layer_norm.bias
            UpperCamelCase__      =							esm_layer.final_layer_norm.weight
            UpperCamelCase__      =							esm_layer.final_layer_norm.bias

            # self-attention output
            UpperCamelCase__      =							layer.attention.output
            assert self_output.dense.weight.shape == esm_layer.self_attn.out_proj.weight.shape
            UpperCamelCase__      =							esm_layer.self_attn.out_proj.weight
            UpperCamelCase__      =							esm_layer.self_attn.out_proj.bias

            # intermediate
            UpperCamelCase__      =							layer.intermediate
            assert intermediate.dense.weight.shape == esm_layer.fca.weight.shape
            UpperCamelCase__      =							esm_layer.fca.weight
            UpperCamelCase__      =							esm_layer.fca.bias

            # output
            UpperCamelCase__      =							layer.output
            assert bert_output.dense.weight.shape == esm_layer.fca.weight.shape
            UpperCamelCase__      =							esm_layer.fca.weight
            UpperCamelCase__      =							esm_layer.fca.bias
            # end of layer

      if is_folding_model:
            UpperCamelCase__      =							esm.esm_s_combine.data
            UpperCamelCase__      =							esm.afa_to_esm.data
            transfer_and_check_weights(esm.embedding ,     model.embedding       )
            transfer_and_check_weights(esm.esm_s_mlp ,     model.esm_s_mlp       )
            transfer_and_check_weights(esm.trunk ,     model.trunk       )
            transfer_and_check_weights(esm.distogram_head ,     model.distogram_head       )
            transfer_and_check_weights(esm.ptm_head ,     model.ptm_head       )
            transfer_and_check_weights(esm.lm_head ,     model.lm_head       )
            transfer_and_check_weights(esm.lddt_head ,     model.lddt_head       )

      elif classification_head:
            UpperCamelCase__      =							esm.esm.classification_heads["mnli"].dense.weight
            UpperCamelCase__      =							esm.classification_heads["mnli"].dense.bias
            UpperCamelCase__      =							esm.classification_heads["mnli"].out_proj.weight
            UpperCamelCase__      =							esm.classification_heads["mnli"].out_proj.bias
      else:
            # LM Head
            UpperCamelCase__      =							esm.lm_head.dense.weight
            UpperCamelCase__      =							esm.lm_head.dense.bias
            UpperCamelCase__      =							esm.lm_head.layer_norm.weight
            UpperCamelCase__      =							esm.lm_head.layer_norm.bias
            UpperCamelCase__      =							esm.lm_head.weight
            UpperCamelCase__      =							esm.lm_head.bias

      # Contact prediction head
      transfer_and_check_weights(esm.contact_head ,     model.esm.contact_head       )

      # Prepare data (first 2 sequences from ESMStructuralSplitDataset superfamily / 4)
      if is_folding_model:
            # Folding models aren't trained on masked inputs and don't like mask tokens.
            UpperCamelCase__      =							SAMPLE_DATA[:2]
      else:
            UpperCamelCase__      =							SAMPLE_DATA

      if is_folding_model:
            UpperCamelCase__      =							get_esmfold_tokenizer()
            UpperCamelCase__      =							hf_tokenizer(
                [row[1] for row in sample_data] ,     return_tensors="pt" ,     padding=__A ,     add_special_tokens=__A       )
            UpperCamelCase__   ,      UpperCamelCase__   ,      UpperCamelCase__   ,      UpperCamelCase__   ,      UpperCamelCase__      =							esmfold_encode_sequences([row[1] for row in sample_data]       )
            UpperCamelCase__      =							torch.all(hf_tokens["input_ids"] == esmfold_aas       ) and torch.all(
                hf_tokens["attention_mask"] == esmfold_mask       )
      else:
            # Let's check that we get the same results.
            UpperCamelCase__      =							alphabet.get_batch_converter()
            UpperCamelCase__   ,      UpperCamelCase__   ,      UpperCamelCase__      =							batch_converter(__A       )
            # Prepare tokenizer and make sure it matches
            with TemporaryDirectory() as tempdir:
                  UpperCamelCase__      =							"\n".join(alphabet.all_toks       )
                  UpperCamelCase__      =							Path(__A       ) / "vocab.txt"
                  vocab_file.write_text(__A       )
                  UpperCamelCase__      =							EsmTokenizer(vocab_file=str(__A       )       )

            UpperCamelCase__      =							hf_tokenizer([row[1] for row in sample_data] ,     return_tensors="pt" ,     padding=__A       )
            UpperCamelCase__      =							torch.all(hf_tokens["input_ids"] == batch_tokens       )

      print("Do both models tokenizers output the same tokens?" ,     "🔥" if success else "💩"       )
      if not success:
            raise Exception("Tokenization does not match!"       )

      with torch.no_grad():
            if is_folding_model:
                  # Let's test the model in parts
                  # ESMFold always converts the ESM stem to float16, which requires float16 ops
                  # that don't exist on CPU. Therefore, to test it we need to run it on GPU. However,
                  # ESMFold is what we in the community call a "big boy" and so we desperately avoid putting both the
                  # original and the converted model on the GPU at the same time.
                  UpperCamelCase__      =							esm.cuda().infer([row[1] for row in sample_data]       )
                  UpperCamelCase__      =							model.cuda()(
                      input_ids=hf_tokens["input_ids"].cuda() ,     attention_mask=hf_tokens["attention_mask"].cuda()       )
            else:
                  UpperCamelCase__      =							model(**__A ,     output_hidden_states=__A       )
                  UpperCamelCase__      =							our_output["logits"]
                  if classification_head:
                        UpperCamelCase__      =							esm.model.classification_heads["mnli"](esm.extract_features(__A       )       )
                  else:
                        UpperCamelCase__      =							esm(hf_tokens["input_ids"] ,     repr_layers=list(range(999       )       )       )
                        UpperCamelCase__      =							their_output["logits"]

            if is_folding_model:
                  UpperCamelCase__      =							torch.max(torch.abs(our_output["positions"] - their_output["positions"]       )       ).item()
                  UpperCamelCase__      =							torch.allclose(our_output["positions"] ,     their_output["positions"] ,     atol=1E-5       )
            else:
                  UpperCamelCase__      =							torch.max(torch.abs(our_output - their_output       )       ).item()
                  UpperCamelCase__      =							torch.allclose(__A ,     __A ,     atol=1E-5       )

            print(F'''max_absolute_diff = {max_absolute_diff}'''       )  # ~ 1e-5
            print("Do both models output the same tensors?" ,     "🔥" if success else "💩"       )

            if not success:
                  raise Exception("Something went wRoNg"       )

            if not is_folding_model:
                  # Let's check contact prediction too
                  UpperCamelCase__      =							model.predict_contacts(hf_tokens["input_ids"] ,     hf_tokens["attention_mask"]       )
                  UpperCamelCase__      =							esm.predict_contacts(hf_tokens["input_ids"]       )
                  UpperCamelCase__      =							torch.max(torch.abs(our_output - their_output       )       ).item()
                  UpperCamelCase__      =							torch.allclose(__A ,     __A ,     atol=1E-5       )

                  print("Contact prediction testing:"       )
                  print(F'''max_absolute_diff = {max_absolute_diff}'''       )  # ~ 1e-5
                  print("Do both models output the same tensors?" ,     "🔥" if success else "💩"       )

                  if not success:
                        raise Exception("Something went wRoNg"       )

            pathlib.Path(__A       ).mkdir(parents=__A ,     exist_ok=__A       )
            print(F'''Saving model to {pytorch_dump_folder_path}'''       )
            model.save_pretrained(__A       )

            del esm  # Free up some memory before continuing

      print(F'''Saving tokenizer to {pytorch_dump_folder_path}'''       )
      hf_tokenizer.save_pretrained(__A       )

      if push_to_repo:
            model.push_to_hub(repo_id=__A ,     use_auth_token=__A       )
            hf_tokenizer.push_to_hub(repo_id=__A ,     use_auth_token=__A       )


if __name__ == "__main__":
  a__    :   str								=			argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--pytorch_dump_folder_path', type=str, required=True, help='Path to the output PyTorch model.'
  )
  parser.add_argument(
      '--classification_head', action='store_true', help='Whether to convert a final classification head.'
  )
  parser.add_argument('--model', default=None, type=str, required=True, help='Name of model to convert.')
  parser.add_argument('--push_to_repo', type=str, help='Repo to upload to (including username!).')
  parser.add_argument('--auth_token', type=str, help='HuggingFace auth token.')
  a__    :   Optional[Any]								=			parser.parse_args()
  convert_esm_checkpoint_to_pytorch(
      args.model, args.pytorch_dump_folder_path, args.classification_head, args.push_to_repo, args.auth_token
  )





