





import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__A									=				logging.get_logger(__name__)

__A									=				"▁"

__A									=				{"vocab_file": "sentencepiece.bpe.model"}

__A									=				{
    "vocab_file": {
        "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model",
    }
}

__A									=				{
    "facebook/xglm-564M": 2048,
}



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 lowercase_		=			VOCAB_FILES_NAMES
 lowercase_		=			PRETRAINED_VOCAB_FILES_MAP
 lowercase_		=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowercase_		=			["input_ids", "attention_mask"]

 def __init__(self				:   List[Any]       , UpperCAmelCase_				:   List[Any]       , UpperCAmelCase_				:   Any="<s>"       , UpperCAmelCase_				:   Optional[int]="</s>"       , UpperCAmelCase_				:   List[Any]="</s>"       , UpperCAmelCase_				:   Union[str, Any]="<s>"       , UpperCAmelCase_				:   Any="<unk>"       , UpperCAmelCase_				:   str="<pad>"       , UpperCAmelCase_				:   Optional[Dict[str, Any]] = None       , **UpperCAmelCase_				:   str       , )       ->None:



   '''simple docstring'''



   lowerCamelCase__:      Dict			  ={} if sp_model_kwargs is None else sp_model_kwargs

   # Compatibility with the original tokenizer
   lowerCamelCase__:      Tuple			  =7
   lowerCamelCase__:      int			  =[F"""<madeupword{i}>""" for i in range(self.num_madeup_words)]

   lowerCamelCase__:      str			  =kwargs.get("additional_special_tokens"       , [])
   kwargs["additional_special_tokens"] += [
       word for word in madeup_words if word not in kwargs["additional_special_tokens"]
   ]

   super().__init__(
       bos_token=UpperCAmelCase_       , eos_token=UpperCAmelCase_       , unk_token=UpperCAmelCase_       , sep_token=UpperCAmelCase_       , cls_token=UpperCAmelCase_       , pad_token=UpperCAmelCase_       , sp_model_kwargs=self.sp_model_kwargs       , **UpperCAmelCase_       , )

   lowerCamelCase__:      Any			  =spm.SentencePieceProcessor(**self.sp_model_kwargs)
   self.sp_model.Load(str(UpperCAmelCase_))
   lowerCamelCase__:      List[str]			  =vocab_file

   # Original fairseq vocab and spm vocab must be "aligned":
   # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
   # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
   # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
   # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

   # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
   lowerCamelCase__:      Union[str, Any]			  =1

   # Mimic fairseq token-to-id alignment for the first 4 token
   lowerCamelCase__:      Union[str, Any]			  ={"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}

   lowerCamelCase__:      Any			  =len(self.sp_model)
   lowerCamelCase__:      Tuple			  ={F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)}
   self.fairseq_tokens_to_ids.update(UpperCAmelCase_)

   lowerCamelCase__:      int			  ={v: k for k, v in self.fairseq_tokens_to_ids.items()}

 def __getstate__(self				:   Dict)       ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =self.__dict__.copy()
   lowerCamelCase__:      str			  =None
   lowerCamelCase__:      Any			  =self.sp_model.serialized_model_proto()
   return state

 def __setstate__(self				:   Any       , UpperCAmelCase_				:   Tuple)       ->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:      Optional[Any]			  =d

   # for backward compatibility
   if not hasattr(self       , "sp_model_kwargs"):
     lowerCamelCase__:      int			  ={}

   lowerCamelCase__:      str			  =spm.SentencePieceProcessor(**self.sp_model_kwargs)
   self.sp_model.LoadFromSerializedProto(self.sp_model_proto)

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str]       , UpperCAmelCase_				:   List[int]       , UpperCAmelCase_				:   Optional[List[int]] = None)       ->List[int]:



   '''simple docstring'''



   if token_ids_a is None:
     return [self.sep_token_id] + token_ids_a
   lowerCamelCase__:      Any			  =[self.sep_token_id]
   return sep + token_ids_a + sep + sep + token_ids_a

 def 							SCREAMING_SNAKE_CASE_					(self				:   int       , UpperCAmelCase_				:   List[int]       , UpperCAmelCase_				:   Optional[List[int]] = None       , UpperCAmelCase_				:   bool = False)       ->List[int]:



   '''simple docstring'''



   if already_has_special_tokens:
     return super().get_special_tokens_mask(
         token_ids_a=UpperCAmelCase_       , token_ids_a=UpperCAmelCase_       , already_has_special_tokens=UpperCAmelCase_)

   if token_ids_a is None:
     return [1] + ([0] * len(UpperCAmelCase_))
   return [1] + ([0] * len(UpperCAmelCase_)) + [1, 1] + ([0] * len(UpperCAmelCase_))

 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict       , UpperCAmelCase_				:   List[int]       , UpperCAmelCase_				:   Optional[List[int]] = None)       ->List[int]:



   '''simple docstring'''



   lowerCamelCase__:      List[str]			  =[self.sep_token_id]

   if token_ids_a is None:
     return len(sep + token_ids_a) * [0]
   return len(sep + token_ids_a + sep + sep + token_ids_a) * [0]

 @property
 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Optional[int]:



   '''simple docstring'''



   return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words

 def 							SCREAMING_SNAKE_CASE_					(self				:   int)       ->str:



   '''simple docstring'''



   lowerCamelCase__:      str			  ={self.convert_ids_to_tokens(UpperCAmelCase_): i for i in range(self.vocab_size)}
   vocab.update(self.added_tokens_encoder)
   return vocab

 def 							SCREAMING_SNAKE_CASE_					(self				:   Any       , UpperCAmelCase_				:   str)       ->List[str]:



   '''simple docstring'''



   return self.sp_model.encode(UpperCAmelCase_       , out_type=UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str]       , UpperCAmelCase_				:   Union[str, Any])       ->Dict:



   '''simple docstring'''



   if token in self.fairseq_tokens_to_ids:
     return self.fairseq_tokens_to_ids[token]
   lowerCamelCase__:      Optional[int]			  =self.sp_model.PieceToId(UpperCAmelCase_)

   # Need to return unknown token if the SP model returned 0
   return spm_id + self.fairseq_offset if spm_id else self.unk_token_id

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str]       , UpperCAmelCase_				:   List[str])       ->Optional[Any]:



   '''simple docstring'''



   if index in self.fairseq_ids_to_tokens:
     return self.fairseq_ids_to_tokens[index]
   return self.sp_model.IdToPiece(index - self.fairseq_offset)

 def 							SCREAMING_SNAKE_CASE_					(self				:   Any       , UpperCAmelCase_				:   Dict)       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      str			  ="".join(UpperCAmelCase_).replace(UpperCAmelCase_       , " ").strip()
   return out_string







 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict       , UpperCAmelCase_				:   str       , UpperCAmelCase_				:   Optional[str] = None)       ->Tuple[str]:



   '''simple docstring'''



   if not os.path.isdir(UpperCAmelCase_):
     logger.error(F"""Vocabulary path ({save_directory}) should be a directory""")
     return
   lowerCamelCase__:      List[str]			  =os.path.join(
       UpperCAmelCase_       , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"])

   if os.path.abspath(self.vocab_file) != os.path.abspath(UpperCAmelCase_) and os.path.isfile(self.vocab_file):
     copyfile(self.vocab_file       , UpperCAmelCase_)
   elif not os.path.isfile(self.vocab_file):
     with open(UpperCAmelCase_       , "wb") as fi:
       lowerCamelCase__:      Optional[int]			  =self.sp_model.serialized_model_proto()
       fi.write(UpperCAmelCase_)

   return (out_vocab_file,)





'''simple docstring'''

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      snake_case    :





  """simple docstring"""




  def __init__(    self			,  UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  parent
   lowerCamelCase_      =  13
   lowerCamelCase_      =  7
   lowerCamelCase_      =  True
   lowerCamelCase_      =  True
   lowerCamelCase_      =  True
   lowerCamelCase_      =  99
   lowerCamelCase_      =  32
   lowerCamelCase_      =  2
   lowerCamelCase_      =  4
   lowerCamelCase_      =  37
   lowerCamelCase_      =  "gelu"
   lowerCamelCase_      =  0.1
   lowerCamelCase_      =  0.1
   lowerCamelCase_      =  512
   lowerCamelCase_      =  16
   lowerCamelCase_      =  2
   lowerCamelCase_      =  0.02
   lowerCamelCase_      =  3
   lowerCamelCase_      =  4
   lowerCamelCase_      =  None






  def   snake_case		(    self     ):







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

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

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

   lowerCamelCase_      =  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   snake_case		(    self     ):







   """simple docstring"""
   (
       (
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,
   )      =  self.prepare_config_and_inputs()

   lowerCamelCase_      =  True
   lowerCamelCase_      =  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
   lowerCamelCase_      =  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   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmModel(config=UpperCamelCase     )
   lowerCamelCase_      =  {"input_ids": input_ids, "attention_mask": input_mask}
   lowerCamelCase_      =  model(UpperCamelCase     )

   lowerCamelCase_      =  [input_ids, input_mask]
   lowerCamelCase_      =  model(UpperCamelCase     )

   lowerCamelCase_      =  model(UpperCamelCase     )

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






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  True

   lowerCamelCase_      =  TFEsmModel(config=UpperCamelCase     )
   lowerCamelCase_      =  {
       "input_ids": input_ids,
       "attention_mask": input_mask,
       "encoder_hidden_states": encoder_hidden_states,
       "encoder_attention_mask": encoder_attention_mask,
   }
   lowerCamelCase_      =  model(UpperCamelCase     )

   lowerCamelCase_      =  [input_ids, input_mask]
   lowerCamelCase_      =  model(UpperCamelCase			,  encoder_hidden_states=UpperCamelCase     )

   # Also check the case where encoder outputs are not passed
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase     )

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






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmForMaskedLM(config=UpperCamelCase     )
   lowerCamelCase_      =  model([input_ids, input_mask]     )
   self.parent.assertEqual(result.logits.shape			,  (self.batch_size, self.seq_length, self.vocab_size)     )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  self.num_labels
   lowerCamelCase_      =  TFEsmForTokenClassification(config=UpperCamelCase     )
   lowerCamelCase_      =  {"input_ids": input_ids, "attention_mask": input_mask}
   lowerCamelCase_      =  model(UpperCamelCase     )
   self.parent.assertEqual(result.logits.shape			,  (self.batch_size, self.seq_length, self.num_labels)     )







  def   snake_case		(    self     ):







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





@require_tf
class      snake_case    (    lowercase			,						lowercase			,						unittest.TestCase			):





  """simple docstring"""




  _lowerCamelCase		    =  (
      (
          TFEsmModel,
          TFEsmForMaskedLM,
          TFEsmForSequenceClassification,
          TFEsmForTokenClassification,
      )
      if is_tf_available()
      else ()
  )
  _lowerCamelCase		    =  (
      {
          "feature-extraction": TFEsmModel,
          "fill-mask": TFEsmForMaskedLM,
          "text-classification": TFEsmForSequenceClassification,
          "token-classification": TFEsmForTokenClassification,
          "zero-shot": TFEsmForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  _lowerCamelCase		    =  False
  _lowerCamelCase		    =  False






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmModelTester(self     )
   lowerCamelCase_      =  ConfigTester(self			,  config_class=UpperCamelCase			,  hidden_size=37     )






  def   snake_case		(    self     ):







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






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_decoder()
   self.model_tester.create_and_check_model_as_decoder(*UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_token_classification(*UpperCamelCase     )






  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    lowerCamelCase_      =  TFEsmModel.from_pretrained(UpperCamelCase     )
    self.assertIsNotNone(UpperCamelCase     )






  @unittest.skip("Protein models do not support embedding resizing."     )
  def   snake_case		(    self     ):







   """simple docstring"""
   pass






  @unittest.skip("Protein models do not support embedding resizing."     )
  def   snake_case		(    self     ):







   """simple docstring"""
   pass







  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_ ,lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    lowerCamelCase_      =  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_      =  model.get_bias()
     assert isinstance(UpperCamelCase			,  UpperCamelCase     )
     for k, v in name.items():
      assert isinstance(UpperCamelCase			,  tf.Variable     )
    else:
     lowerCamelCase_      =  model.get_output_embeddings()
     assert x is None
     lowerCamelCase_      =  model.get_bias()
     assert name is None





@require_tf
class      snake_case    (    unittest.TestCase			):





  """simple docstring"""




  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"     )

   lowerCamelCase_      =  tf.constant([[0, 1, 2, 3, 4, 5]]     )
   lowerCamelCase_      =  model(UpperCamelCase     )[0]
   lowerCamelCase_      =  [1, 6, 33]
   self.assertEqual(list(output.numpy().shape     )			,  UpperCamelCase     )
   # compare the actual values for a slice.
   lowerCamelCase_      =  tf.constant(
       [
           [
               [8.921_518, -10.589_814, -6.4_671_307],
               [-6.3_967_156, -13.911_377, -1.1_211_915],
               [-7.781_247, -13.951_557, -3.740_592],
           ]
       ]     )
   self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()			,  expected_slice.numpy()			,  atol=1e-2     )     )







  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"     )

   lowerCamelCase_      =  tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]     )
   lowerCamelCase_      =  model(UpperCamelCase     )[0]
   # compare the actual values for a slice.
   lowerCamelCase_      =  tf.constant(
       [
           [
               [0.14_443_092, 0.54_125_327, 0.3_247_739],
               [0.30_340_484, 0.00_526_676, 0.31_077_722],
               [0.32_278_043, -0.24_987_096, 0.3_414_628],
           ]
       ]     )
   self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()			,  expected_slice.numpy()			,  atol=1e-4     )     )



