import pickle
import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


__lowercase											=      get_tests_dir('''fixtures/test_sentencepiece.model''')


@require_sentencepiece
@require_tokenizers
class 			lowerCamelCase_  (     UpperCAmelCase_		,			unittest.TestCase				):






    '''simple docstring'''






    a__			:		List[str]      			=   XGLMTokenizer
    a__			:		int      			=   XGLMTokenizerFast
    a__			:		Tuple      			=   True
    a__			:		List[Any]      			=   True







    def     UpperCamelCase__     (			self) ->			List[Any]:
        super().setUp()

        # We have a SentencePiece fixture for testing
        __UpperCamelCase  :int    						=	XGLMTokenizer(__lowercase				,				keep_accents=__lowercase)
        tokenizer.save_pretrained(self.tmpdirname)







    def     UpperCamelCase__     (			self) ->			List[Any]:
        __UpperCamelCase  :str    						=	'''<pad>'''
        __UpperCamelCase  :Union[str, Any]    						=	1

        self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowercase)				,				__lowercase)
        self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowercase)				,				__lowercase)







    def     UpperCamelCase__     (			self) ->			int:
        __UpperCamelCase  :str    						=	list(self.get_tokenizer().get_vocab().keys())

        self.assertEqual(vocab_keys[0]				,				'''<s>''')
        self.assertEqual(vocab_keys[1]				,				'''<pad>''')
        self.assertEqual(len(__lowercase)				,				1_008)







    def     UpperCamelCase__     (			self) ->			Optional[int]:
        self.assertEqual(self.get_tokenizer().vocab_size				,				1_008)







    def     UpperCamelCase__     (			self) ->			Dict:
        __UpperCamelCase  :Optional[Any]    						=	XGLMTokenizer(__lowercase				,				keep_accents=__lowercase)

        __UpperCamelCase  :Optional[int]    						=	tokenizer.tokenize('''This is a test''')
        self.assertListEqual(__lowercase				,				['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''])

        self.assertListEqual(
            tokenizer.convert_tokens_to_ids(__lowercase)				,				[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]				,				)

        __UpperCamelCase  :str    						=	tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
        self.assertListEqual(
            __lowercase				,				[
                SPIECE_UNDERLINE + '''I''',
                SPIECE_UNDERLINE + '''was''',
                SPIECE_UNDERLINE + '''b''',
                '''or''',
                '''n''',
                SPIECE_UNDERLINE + '''in''',
                SPIECE_UNDERLINE + '''''',
                '''9''',
                '''2''',
                '''0''',
                '''0''',
                '''0''',
                ''',''',
                SPIECE_UNDERLINE + '''and''',
                SPIECE_UNDERLINE + '''this''',
                SPIECE_UNDERLINE + '''is''',
                SPIECE_UNDERLINE + '''f''',
                '''al''',
                '''s''',
                '''é''',
                '''.''',
            ]				,				)
        __UpperCamelCase  :Optional[int]    						=	tokenizer.convert_tokens_to_ids(__lowercase)
        self.assertListEqual(
            __lowercase				,				[
                value + tokenizer.fairseq_offset
                for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
            ]				,				)

        __UpperCamelCase  :Union[str, Any]    						=	tokenizer.convert_ids_to_tokens(__lowercase)
        self.assertListEqual(
            __lowercase				,				[
                SPIECE_UNDERLINE + '''I''',
                SPIECE_UNDERLINE + '''was''',
                SPIECE_UNDERLINE + '''b''',
                '''or''',
                '''n''',
                SPIECE_UNDERLINE + '''in''',
                SPIECE_UNDERLINE + '''''',
                '''<unk>''',
                '''2''',
                '''0''',
                '''0''',
                '''0''',
                ''',''',
                SPIECE_UNDERLINE + '''and''',
                SPIECE_UNDERLINE + '''this''',
                SPIECE_UNDERLINE + '''is''',
                SPIECE_UNDERLINE + '''f''',
                '''al''',
                '''s''',
                '''<unk>''',
                '''.''',
            ]				,				)







    @cached_property
    def     UpperCamelCase__     (			self) ->			Any:
        return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''')







    def     UpperCamelCase__     (			self) ->			Tuple:
        with tempfile.NamedTemporaryFile() as f:
            shutil.copyfile(__lowercase				,				f.name)
            __UpperCamelCase  :Optional[Any]    						=	XGLMTokenizer(f.name				,				keep_accents=__lowercase)
            __UpperCamelCase  :int    						=	pickle.dumps(__lowercase)
        pickle.loads(__lowercase)







    def     UpperCamelCase__     (			self) ->			Tuple:
        if not self.test_rust_tokenizer:
            return

        __UpperCamelCase  :Any    						=	self.get_tokenizer()
        __UpperCamelCase  :List[str]    						=	self.get_rust_tokenizer()

        __UpperCamelCase  :Union[str, Any]    						=	'''I was born in 92000, and this is falsé.'''

        __UpperCamelCase  :str    						=	tokenizer.tokenize(__lowercase)
        __UpperCamelCase  :Union[str, Any]    						=	rust_tokenizer.tokenize(__lowercase)
        self.assertListEqual(__lowercase				,				__lowercase)

        __UpperCamelCase  :int    						=	tokenizer.encode(__lowercase				,				add_special_tokens=__lowercase)
        __UpperCamelCase  :Union[str, Any]    						=	rust_tokenizer.encode(__lowercase				,				add_special_tokens=__lowercase)
        self.assertListEqual(__lowercase				,				__lowercase)

        __UpperCamelCase  :Union[str, Any]    						=	self.get_rust_tokenizer()
        __UpperCamelCase  :Optional[Any]    						=	tokenizer.encode(__lowercase)
        __UpperCamelCase  :Dict    						=	rust_tokenizer.encode(__lowercase)
        self.assertListEqual(__lowercase				,				__lowercase)







    @slow
    def     UpperCamelCase__     (			self) ->			int:
        __UpperCamelCase  :Tuple    						=	'''Hello World!'''
        __UpperCamelCase  :Union[str, Any]    						=	[2, 31_227, 4_447, 35]

        self.assertListEqual(__lowercase				,				self.big_tokenizer.encode(__lowercase))







    @slow
    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        __UpperCamelCase  :Tuple    						=	(
            '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'''
            ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth'''
        )
        # fmt: off
        __UpperCamelCase  :Any    						=	[2, 1_018, 67, 11, 1_988, 2_617, 5_631, 278, 11, 3_407, 48, 71_630, 28_085, 4, 3_234, 157, 13, 6, 5, 6, 4, 3_526, 768, 15, 659, 57, 298, 3_983, 864, 129, 21, 6, 5, 13_675, 377, 652, 7_580, 10_341, 155, 2_817, 422, 1_666, 7, 1_674, 53, 113, 202_277, 17_892, 33, 60, 87, 4, 3_234, 157, 61, 2_667, 52_376, 19, 88, 23, 735]
        # fmt: on

        self.assertListEqual(__lowercase				,				self.big_tokenizer.encode(__lowercase))







    @slow
    def     UpperCamelCase__     (			self) ->			List[str]:
        # fmt: off
        __UpperCamelCase  :Optional[int]    						=	{
            '''input_ids''': [[2, 108_825, 1_163, 15, 88_010, 473, 15_898, 157, 13_672, 1_857, 312, 8, 238_021, 1_163, 53, 13_672, 1_857, 312, 8, 53_283, 182_396, 8, 18_566, 16, 36_733, 4_101, 8, 230, 244_017, 122_553, 7, 15, 132_597, 4, 293, 12_511, 7_610, 4, 3_414, 132_597, 9, 4, 32_361, 362, 4, 734, 28_512, 32_569, 18, 4, 32_361, 26_096, 14_982, 73, 18_715, 21_433, 235_261, 15, 492, 12_427, 16, 53, 18_715, 21_433, 65_454, 15, 23_659, 563, 16, 278, 597, 2_843, 595, 7_931, 182_396, 64_186, 22, 886, 595, 132_981, 53, 25_540, 3_449, 43_982, 39_901, 5_951, 878, 330, 4, 27_694, 80_269, 312, 53, 6_517, 11_780, 611, 20_408, 5], [2, 6, 132_597, 67, 42_897, 33, 592, 8, 163_729, 25_540, 361, 136_997, 109_514, 173_230, 7, 501, 60, 102_913, 196, 5_631, 235, 63_243, 473, 6, 231_757, 74, 5_277, 7_905, 53, 3_095, 37_317, 22, 454, 183_874, 5], [2, 268, 31_298, 46_530, 6, 132_935, 43_831, 7, 597, 32, 24, 3_688, 9_865, 5]],
            '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
        }  # noqa: E501
        # fmt: on

        self.tokenizer_integration_test_util(
            expected_encoding=__lowercase				,				model_name='''facebook/xglm-564M'''				,				padding=__lowercase				,				)






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






    '''simple docstring'''






    def __init__(			self				,				__lowercase				,				__lowercase=13				,				__lowercase=7				,				__lowercase=False				,				__lowercase=True				,				__lowercase=False				,				__lowercase=False				,				__lowercase=19				,				__lowercase=32				,				__lowercase=5				,				__lowercase=4				,				__lowercase=37				,				__lowercase="gelu"				,				__lowercase=0.1				,				__lowercase=0.1				,				__lowercase=512				,				__lowercase=16				,				__lowercase=2				,				__lowercase=0.02				,				__lowercase=3				,				__lowercase=4				,				__lowercase=None				,				) ->			Optional[Any]:
        __UpperCamelCase  :Dict    						=	parent
        __UpperCamelCase  :Optional[Any]    						=	batch_size
        __UpperCamelCase  :Any    						=	seq_length
        __UpperCamelCase  :List[str]    						=	is_training
        __UpperCamelCase  :Any    						=	use_input_mask
        __UpperCamelCase  :Optional[int]    						=	use_token_type_ids
        __UpperCamelCase  :List[str]    						=	use_labels
        __UpperCamelCase  :Tuple    						=	vocab_size
        __UpperCamelCase  :List[Any]    						=	hidden_size
        __UpperCamelCase  :Optional[Any]    						=	num_hidden_layers
        __UpperCamelCase  :List[Any]    						=	num_attention_heads
        __UpperCamelCase  :Dict    						=	intermediate_size
        __UpperCamelCase  :List[str]    						=	hidden_act
        __UpperCamelCase  :Any    						=	hidden_dropout_prob
        __UpperCamelCase  :Union[str, Any]    						=	attention_probs_dropout_prob
        __UpperCamelCase  :Optional[Any]    						=	max_position_embeddings
        __UpperCamelCase  :List[Any]    						=	type_vocab_size
        __UpperCamelCase  :int    						=	type_sequence_label_size
        __UpperCamelCase  :str    						=	initializer_range
        __UpperCamelCase  :Optional[Any]    						=	num_labels
        __UpperCamelCase  :int    						=	num_choices
        __UpperCamelCase  :Optional[Any]    						=	scope







    def     UpperCamelCase__     (			self) ->			List[Any]:
        __UpperCamelCase  :int    						=	ids_tensor([self.batch_size, self.seq_length]				,				self.vocab_size)

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

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

        __UpperCamelCase  :Optional[Any]    						=	self.get_config()

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







    def     UpperCamelCase__     (			self) ->			Optional[int]:
        __UpperCamelCase  :int    						=	EsmConfig(
            vocab_size=33				,				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=__lowercase				,				esmfold_config={'''trunk''': {'''num_blocks''': 2}, '''fp16_esm''': False}				,				)
        return config







    def     UpperCamelCase__     (			self				,				__lowercase				,				__lowercase				,				__lowercase				,				__lowercase				,				__lowercase				,				__lowercase) ->			Union[str, Any]:
        __UpperCamelCase  :int    						=	EsmForProteinFolding(config=__lowercase).float()
        model.to(__lowercase)
        model.eval()
        __UpperCamelCase  :Tuple    						=	model(__lowercase				,				attention_mask=__lowercase)
        __UpperCamelCase  :Any    						=	model(__lowercase)
        __UpperCamelCase  :Optional[Any]    						=	model(__lowercase)

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







    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        __UpperCamelCase  :Dict    						=	self.prepare_config_and_inputs()
        (
            (
            __UpperCamelCase
        )						, (
            __UpperCamelCase
        )						, (
            __UpperCamelCase
        )						, (
            __UpperCamelCase
        )						, (
            __UpperCamelCase
        )						, (
            __UpperCamelCase
        )						, 
        )  :List[str]    						=	config_and_inputs
        __UpperCamelCase  :Tuple    						=	{'''input_ids''': input_ids, '''attention_mask''': input_mask}
        return config, inputs_dict


@require_torch
class 			lowerCamelCase_  (     UpperCAmelCase_		,			UpperCAmelCase_		,			unittest.TestCase				):






    '''simple docstring'''






    a__			:		Optional[int]      			=   False

    a__			:		Optional[int]      			=   (EsmForProteinFolding,) if is_torch_available() else ()
    a__			:		str      			=   ()
    a__			:		Tuple      			=   {} if is_torch_available() else {}
    a__			:		List[Any]      			=   False







    def     UpperCamelCase__     (			self) ->			Tuple:
        __UpperCamelCase  :Dict    						=	EsmFoldModelTester(self)
        __UpperCamelCase  :Dict    						=	ConfigTester(self				,				config_class=__lowercase				,				hidden_size=37)







    def     UpperCamelCase__     (			self) ->			List[Any]:
        self.config_tester.run_common_tests()







    def     UpperCamelCase__     (			self) ->			List[str]:
        __UpperCamelCase  :Any    						=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase)







    @unittest.skip('''Does not support attention outputs''')
    def     UpperCamelCase__     (			self) ->			Any:
        pass







    @unittest.skip
    def     UpperCamelCase__     (			self) ->			Any:
        pass







    @unittest.skip('''Esm does not support embedding resizing''')
    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        pass







    @unittest.skip('''Esm does not support embedding resizing''')
    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        pass







    @unittest.skip('''ESMFold does not support passing input embeds!''')
    def     UpperCamelCase__     (			self) ->			List[Any]:
        pass







    @unittest.skip('''ESMFold does not support head pruning.''')
    def     UpperCamelCase__     (			self) ->			Optional[int]:
        pass







    @unittest.skip('''ESMFold does not support head pruning.''')
    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        pass







    @unittest.skip('''ESMFold does not support head pruning.''')
    def     UpperCamelCase__     (			self) ->			Dict:
        pass







    @unittest.skip('''ESMFold does not support head pruning.''')
    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        pass







    @unittest.skip('''ESMFold does not support head pruning.''')
    def     UpperCamelCase__     (			self) ->			Optional[int]:
        pass







    @unittest.skip('''ESMFold does not output hidden states in the normal way.''')
    def     UpperCamelCase__     (			self) ->			str:
        pass







    @unittest.skip('''ESMfold does not output hidden states in the normal way.''')
    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        pass







    @unittest.skip('''ESMFold only has one output format.''')
    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        pass







    @unittest.skip('''This test doesn\'t work for ESMFold and doesn\'t test core functionality''')
    def     UpperCamelCase__     (			self) ->			List[Any]:
        pass







    @unittest.skip('''ESMFold does not support input chunking.''')
    def     UpperCamelCase__     (			self) ->			List[Any]:
        pass







    @unittest.skip('''ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.''')
    def     UpperCamelCase__     (			self) ->			int:
        pass







    @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''')
    def     UpperCamelCase__     (			self) ->			str:
        pass







    @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''')
    def     UpperCamelCase__     (			self) ->			List[Any]:
        pass







    @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''')
    def     UpperCamelCase__     (			self) ->			List[Any]:
        pass







    @unittest.skip('''ESMFold doesn\'t support data parallel.''')
    def     UpperCamelCase__     (			self) ->			Any:
        pass







    @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
    def     UpperCamelCase__     (			self) ->			Dict:
        pass


@require_torch
class 			lowerCamelCase_  (     UpperCAmelCase_				):






    '''simple docstring'''






    @slow
    def     UpperCamelCase__     (			self) ->			Tuple:
        __UpperCamelCase  :Optional[Any]    						=	EsmForProteinFolding.from_pretrained('''facebook/esmfold_v1''').float()
        model.eval()
        __UpperCamelCase  :Tuple    						=	torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
        __UpperCamelCase  :List[Any]    						=	model(__lowercase)['''positions''']
        __UpperCamelCase  :Optional[int]    						=	torch.tensor([2.58_28, 0.79_93, -10.93_34]				,				dtype=torch.floataa)
        self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0]				,				__lowercase				,				atol=1E-4))





