
'''simple docstring'''






import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, 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.models.esm.modeling_esmfold import EsmForProteinFolding

class  UpperCAmelCase__						:



    def __init__(	self      :       Optional[int],__A      :       Union[str, Any],__A      :       Union[str, Any]=1_3,__A      :       Union[str, Any]=7,__A      :       Tuple=False,__A      :       int=True,__A      :       int=False,__A      :       List[str]=False,__A      :       int=1_9,__A      :       Optional[Any]=3_2,__A      :       int=5,__A      :       str=4,__A      :       Optional[int]=3_7,__A      :       Dict="gelu",__A      :       Union[str, Any]=0.1,__A      :       List[str]=0.1,__A      :       Optional[Any]=5_1_2,__A      :       Optional[Any]=1_6,__A      :       Union[str, Any]=2,__A      :       Union[str, Any]=0.02,__A      :       str=3,__A      :       Optional[Any]=4,__A      :       str=None,):
          _lowerCamelCase				:   Any								=   parent
          _lowerCamelCase				:   Dict								=   batch_size
          _lowerCamelCase				:   str								=   seq_length
          _lowerCamelCase				:   int								=   is_training
          _lowerCamelCase				:   Tuple								=   use_input_mask
          _lowerCamelCase				:   List[Any]								=   use_token_type_ids
          _lowerCamelCase				:   Optional[int]								=   use_labels
          _lowerCamelCase				:   Any								=   vocab_size
          _lowerCamelCase				:   Dict								=   hidden_size
          _lowerCamelCase				:   Optional[int]								=   num_hidden_layers
          _lowerCamelCase				:   int								=   num_attention_heads
          _lowerCamelCase				:   str								=   intermediate_size
          _lowerCamelCase				:   Tuple								=   hidden_act
          _lowerCamelCase				:   Union[str, Any]								=   hidden_dropout_prob
          _lowerCamelCase				:   Union[str, Any]								=   attention_probs_dropout_prob
          _lowerCamelCase				:   Optional[int]								=   max_position_embeddings
          _lowerCamelCase				:   Tuple								=   type_vocab_size
          _lowerCamelCase				:   int								=   type_sequence_label_size
          _lowerCamelCase				:   List[str]								=   initializer_range
          _lowerCamelCase				:   Optional[int]								=   num_labels
          _lowerCamelCase				:   int								=   num_choices
          _lowerCamelCase				:   Dict								=   scope



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   List[Any]								=   ids_tensor([self.batch_size, self.seq_length],self.vocab_size     )

          _lowerCamelCase				:   Optional[Any]								=   None
          if self.use_input_mask:
                _lowerCamelCase				:   Tuple								=   random_attention_mask([self.batch_size, self.seq_length]     )

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

          _lowerCamelCase				:   Union[str, Any]								=   self.get_config()

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



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   List[Any]								=   EsmConfig(
              vocab_size=3_3,hidden_size=self.hidden_size,pad_token_id=1,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,is_folding_model=__A,esmfold_config={"trunk": {"num_blocks": 2}, "fp16_esm": False},)
          return config



    def   lowerCamelCase_  (	self      :       Any,__A      :       Optional[Any],__A      :       int,__A      :       List[Any],__A      :       Tuple,__A      :       int,__A      :       Union[str, Any]     ):
          _lowerCamelCase				:   int								=   EsmForProteinFolding(config=__A     ).float()
          model.to(__A     )
          model.eval()
          _lowerCamelCase				:   int								=   model(__A,attention_mask=__A     )
          _lowerCamelCase				:   Optional[int]								=   model(__A     )
          _lowerCamelCase				:   Optional[int]								=   model(__A     )

          self.parent.assertEqual(result.positions.shape,(8, self.batch_size, self.seq_length, 1_4, 3)     )
          self.parent.assertEqual(result.angles.shape,(8, self.batch_size, self.seq_length, 7, 2)     )



    def   lowerCamelCase_  (	self      :       Any     ):
          _lowerCamelCase				:   Union[str, Any]								=   self.prepare_config_and_inputs()
          (
              (
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		
          )				:   Dict								=   config_and_inputs
          _lowerCamelCase				:   List[str]								=   {"input_ids": input_ids, "attention_mask": input_mask}
          return config, inputs_dict


@require_torch
class  UpperCAmelCase__						(       A						,	A						,	unittest.TestCase ):
    lowerCAmelCase_				    =		False

    lowerCAmelCase_				    =		(EsmForProteinFolding,) if is_torch_available() else ()
    lowerCAmelCase_				    =		()
    lowerCAmelCase_				    =		{} if is_torch_available() else {}
    lowerCAmelCase_				    =		False



    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          _lowerCamelCase				:   Any								=   EsmFoldModelTester(self     )
          _lowerCamelCase				:   str								=   ConfigTester(self,config_class=__A,hidden_size=3_7     )



    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          self.config_tester.run_common_tests()



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   Tuple								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__A     )



    @unittest.skip("Does not support attention outputs"     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip
    def   lowerCamelCase_  (	self      :       Any     ):
          pass



    @unittest.skip("Esm does not support embedding resizing"     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @unittest.skip("Esm does not support embedding resizing"     )
    def   lowerCamelCase_  (	self      :       Any     ):
          pass



    @unittest.skip("ESMFold does not support passing input embeds!"     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       int     ):
          pass



    @unittest.skip("ESMFold does not output hidden states in the normal way."     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMfold does not output hidden states in the normal way."     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip("ESMFold only has one output format."     )
    def   lowerCamelCase_  (	self      :       Tuple     ):
          pass



    @unittest.skip("This test doesn't work for ESMFold and doesn't test core functionality"     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @unittest.skip("ESMFold does not support input chunking."     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @unittest.skip("ESMFold doesn't respect you and it certainly doesn't respect your initialization arguments."     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMFold doesn't support torchscript compilation."     )
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          pass



    @unittest.skip("ESMFold doesn't support torchscript compilation."     )
    def   lowerCamelCase_  (	self      :       Any     ):
          pass



    @unittest.skip("ESMFold doesn't support torchscript compilation."     )
    def   lowerCamelCase_  (	self      :       List[str]     ):
          pass



    @unittest.skip("ESMFold doesn't support data parallel."     )
    def   lowerCamelCase_  (	self      :       Tuple     ):
          pass



    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."     )
    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          pass


@require_torch
class  UpperCAmelCase__						(       A ):



    @slow
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   Any								=   EsmForProteinFolding.from_pretrained("facebook/esmfold_v1"     ).float()
          model.eval()
          _lowerCamelCase				:   Dict								=   torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]     )
          _lowerCamelCase				:   Tuple								=   model(__A     )["positions"]
          _lowerCamelCase				:   Optional[int]								=   torch.tensor([2.5828, 0.7993, -10.9334],dtype=torch.floataa     )
          self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0],__A,atol=1e-4     )     )

'''simple docstring'''






import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging


if is_torch_available():
 import torch


if TYPE_CHECKING:
 from transformers.pipelines.conversational import Conversation


UpperCAmelCase_       :   str   =       logging.get_logger(__name__)
UpperCAmelCase_       :   Optional[int]   =       {'vocab_file': 'spiece.model'}

UpperCAmelCase_       :   Any   =       {
    'vocab_file': {
        'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model',
    }
}

UpperCAmelCase_       :   str   =       {
    'AI-Sweden/gpt-sw3-126m': 2048,
    'AI-Sweden/gpt-sw3-350m': 2048,
    'AI-Sweden/gpt-sw3-1.6b': 2048,
    'AI-Sweden/gpt-sw3-6.7b': 2048,
    'AI-Sweden/gpt-sw3-20b': 2048,
}

class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		VOCAB_FILES_NAMES
    lowerCAmelCase_				    =		PRETRAINED_VOCAB_FILES_MAP
    lowerCAmelCase_				    =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    lowerCAmelCase_				    =		['input_ids', 'attention_mask']



    def __init__(	self      :       Dict,__A      :       List[str],__A      :       Any=False,__A      :       Tuple=False,__A      :       Dict=False,__A      :       str=None,__A      :       List[str]=None,__A      :       Any=None,__A      :       str=None,__A      :       Optional[Dict[str, Any]] = None,**__A      :       str,):
          _lowerCamelCase				:   List[Any]								=   {} if sp_model_kwargs is None else sp_model_kwargs

          _lowerCamelCase				:   int								=   kwargs.get("name_or_path"     )
          if name_or_path is None:
                logger.warning(
                    "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"
                    " you are testing the model, this can safely be ignored"     )
                _lowerCamelCase				:   Union[str, Any]								=   "None"

          # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
          _lowerCamelCase				:   Tuple								=   "<|endoftext|>" if eos_token is None else eos_token
          _lowerCamelCase				:   List[str]								=   "<unk>" if unk_token is None else unk_token
          if "gpt-sw3-7b" in name_or_path:
                _lowerCamelCase				:   Union[str, Any]								=   unk_token if pad_token is None else pad_token
                _lowerCamelCase				:   str								=   eos_token if bos_token is None else bos_token
          else:
                _lowerCamelCase				:   List[str]								=   "<pad>" if pad_token is None else pad_token
                _lowerCamelCase				:   str								=   "<s>" if bos_token is None else bos_token

          super().__init__(
              do_lower_case=__A,remove_space=__A,keep_accents=__A,bos_token=__A,eos_token=__A,unk_token=__A,pad_token=__A,sp_model_kwargs=self.sp_model_kwargs,**__A,)

          _lowerCamelCase				:   Union[str, Any]								=   do_lower_case
          _lowerCamelCase				:   List[Any]								=   remove_space
          _lowerCamelCase				:   str								=   keep_accents
          _lowerCamelCase				:   List[Any]								=   vocab_file

          _lowerCamelCase				:   int								=   spm.SentencePieceProcessor(**self.sp_model_kwargs     )
          self.sp_model.Load(__A     )

          # Used for whitespace normalization in input texts
          # fmt : off
          _lowerCamelCase				:   Union[str, Any]								=   {" ", " ", " ", " ", " ", "　", " ", " ", " ", " ", "￼", ""}
          # fmt : on

          # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
          _lowerCamelCase				:   int								=   re.compile(
              f'[{"".join(map(__A,list(range(0,9     )     ) + list(range(1_1,3_2     )     ) + list(range(1_2_7,1_6_0     )     ) + [1_6_0, 1_7_3, 8_2_0_3]     )     )}]'     )



    def __getstate__(	self      :       Dict     ):
          _lowerCamelCase				:   int								=   self.__dict__.copy()
          _lowerCamelCase				:   Optional[Any]								=   None
          return state



    def __setstate__(	self      :       Tuple,__A      :       int     ):
          _lowerCamelCase				:   Optional[int]								=   d

          # for backward compatibility
          if not hasattr(self,"sp_model_kwargs"     ):
                _lowerCamelCase				:   List[str]								=   {}

          _lowerCamelCase				:   Tuple								=   spm.SentencePieceProcessor(**self.sp_model_kwargs     )
          self.sp_model.Load(self.vocab_file     )



    @property
    # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
    def   lowerCamelCase_  (	self      :       int     ):
          return len(self.sp_model     )



    def   lowerCamelCase_  (	self      :       Dict,__A      :       str     ):
          _lowerCamelCase				:   Union[str, Any]								=   self.non_printing_characters_re.sub("",__A     )

          # Normalize whitespaces
          _lowerCamelCase				:   Optional[Any]								=   "".join([char if char not in self.whitespaces else " " for char in text]     )

          # NFC Unicode normalization
          _lowerCamelCase				:   Optional[Any]								=   unicodedata.normalize("NFC",__A     )
          return text



    def   lowerCamelCase_  (	self      :       Union[str, Any],__A      :       str,**__A      :       Optional[int]     ):
          _lowerCamelCase				:   str								=   self.preprocess_text(__A     )
          return self.sp_model.encode(__A,out_type=__A     )



    def   lowerCamelCase_  (	self      :       int,__A      :       str     ):
          return self.sp_model.PieceToId(__A     )



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       int     ):
          return self.sp_model.IdToPiece(__A     )



    @staticmethod
    def   lowerCamelCase_  (	__A      :       str     ):
          return out_string



    def   lowerCamelCase_  (	self      :       str,__A      :       List[str]     ):
          _lowerCamelCase				:   str								=   []
          _lowerCamelCase				:   List[Any]								=   ""
          _lowerCamelCase				:   Tuple								=   False
          for token in tokens:
                # make sure that special tokens are not decoded using sentencepiece model
                if token in self.all_special_tokens:
                      # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
                      if not prev_is_special:
                            out_string += " "

                      out_string += self.sp_model.decode(__A     ) + token
                      _lowerCamelCase				:   Optional[int]								=   True
                      _lowerCamelCase				:   Optional[Any]								=   []
                else:
                      current_sub_tokens.append(__A     )
                      _lowerCamelCase				:   str								=   False
          out_string += self.sp_model.decode(__A     )

          return out_string



    def   lowerCamelCase_  (	self      :       Any     ):
          _lowerCamelCase				:   Optional[int]								=   {self.convert_ids_to_tokens(__A     ): i for i in range(self.vocab_size     )}
          vocab.update(self.added_tokens_encoder     )
          return vocab



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       str,__A      :       Optional[str] = None     ):
          if not os.path.isdir(__A     ):
                logger.error(f'Vocabulary path ({save_directory}) should be a directory'     )
                return
          _lowerCamelCase				:   List[Any]								=   os.path.join(
              __A,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]     )

          if os.path.abspath(self.vocab_file     ) != os.path.abspath(__A     ) and os.path.isfile(self.vocab_file     ):
                copyfile(self.vocab_file,__A     )
          elif not os.path.isfile(self.vocab_file     ):
                with open(__A,"wb"     ) as fi:
                      _lowerCamelCase				:   str								=   self.sp_model.serialized_model_proto()
                      fi.write(__A     )

          return (out_vocab_file,)



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       Union[str, List[str]],__A      :       Union[str, bool] = False     ):

          if isinstance(__A,__A     ):
                _lowerCamelCase				:   List[Any]								=   self.preprocess_text(__A     )
                _lowerCamelCase				:   Optional[Any]								=   self.sp_model.encode(__A     )
          else:
                _lowerCamelCase				:   List[str]								=   [self.preprocess_text(__A     ) for t in text]
                _lowerCamelCase				:   int								=   self.sp_model.encode(__A     )

          if return_tensors is True or return_tensors == "pt":
                _lowerCamelCase				:   str								=   torch.tensor(__A     )

          return token_ids



    def   lowerCamelCase_  (	self      :       List[Any],__A      :       Union[int, List[int]]     ):
          return self.sp_model.decode(__A     )



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       "Conversation"     ):
          _lowerCamelCase				:   Any								=   [f'User: {text}' if is_user else f'Bot: {text}' for is_user, text in conversation.iter_texts()]
          _lowerCamelCase				:   Tuple								=   (
              f'{self.eos_token}{self.bos_token}' + f'{self.bos_token}'.join(__A     ) + f'{self.bos_token}Bot:'
          )
          return self.encode(text=__A     )