


import pickle
import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast
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


A			:						List[Any]        =  get_tests_dir('fixtures/test_sentencepiece.model')



@require_sentencepiece
@require_tokenizers
class 				A       (			UpperCAmelCase__					,    unittest.TestCase				):
					'''simple docstring'''






					A__     =					XLMRobertaTokenizer
					A__     =					XLMRobertaTokenizerFast
					A__     =					True
					A__     =					True

					def     lowerCamelCase__	(self       :		List[str]						)		->  List[Any]:




							"""simple docstring"""


							super().setUp()

							# We have a SentencePiece fixture for testing
							lowercase__	     =						XLMRobertaTokenizer(_UpperCAmelCase ,   keep_accents=_UpperCAmelCase						)
							tokenizer.save_pretrained(self.tmpdirname						)

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




							"""simple docstring"""


							lowercase__	     =						"""<pad>"""
							lowercase__	     =						1

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

					def     lowerCamelCase__	(self       :		List[Any]						)		->  int:




							"""simple docstring"""


							lowercase__	     =						list(self.get_tokenizer().get_vocab().keys()						)

							self.assertEqual(vocab_keys[0] ,   """<s>"""						)
							self.assertEqual(vocab_keys[1] ,   """<pad>"""						)
							self.assertEqual(vocab_keys[-1] ,   """<mask>"""						)
							self.assertEqual(len(_UpperCAmelCase						) ,   1002						)

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




							"""simple docstring"""


							self.assertEqual(self.get_tokenizer().vocab_size ,   1002						)

					def     lowerCamelCase__	(self       :		Any						)		->  Any:




							"""simple docstring"""


							lowercase__	     =						XLMRobertaTokenizer(_UpperCAmelCase ,   keep_accents=_UpperCAmelCase						)

							lowercase__	     =						tokenizer.tokenize("""This is a test"""						)
							self.assertListEqual(_UpperCAmelCase ,   ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]						)

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

							lowercase__	     =						tokenizer.tokenize("""I was born in 92000, and this is falsé."""						)
							self.assertListEqual(
							    _UpperCAmelCase ,   [
							        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""",
							        """é""",
							        """.""",
							    ] ,   )
							lowercase__	     =						tokenizer.convert_tokens_to_ids(_UpperCAmelCase						)
							self.assertListEqual(
							    _UpperCAmelCase ,   [
							        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]
							        #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
							    ] ,   )

							lowercase__	     =						tokenizer.convert_ids_to_tokens(_UpperCAmelCase						)
							self.assertListEqual(
							    _UpperCAmelCase ,   [
							        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>""",
							        """.""",
							    ] ,   )

					def     lowerCamelCase__	(self       :		Optional[Any]						)		->  str:




							"""simple docstring"""


							if not self.test_slow_tokenizer:
									# as we don't have a slow version, we can't compare the outputs between slow and fast versions
									return

							lowercase__	     =						(self.rust_tokenizer_class, """hf-internal-testing/tiny-xlm-roberta""", {})
							for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
									with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''						):
											lowercase__	     =						self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase ,   **_UpperCAmelCase						)
											lowercase__	     =						self.tokenizer_class.from_pretrained(_UpperCAmelCase ,   **_UpperCAmelCase						)

											lowercase__	     =						tempfile.mkdtemp()

											lowercase__	     =						tokenizer_r.save_pretrained(_UpperCAmelCase						)
											lowercase__	     =						tokenizer_p.save_pretrained(_UpperCAmelCase						)

											# Checks it save with the same files + the tokenizer.json file for the fast one
											self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files						)						)
											lowercase__	     =						tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f						)
											self.assertSequenceEqual(_UpperCAmelCase ,   _UpperCAmelCase						)

											# Checks everything loads correctly in the same way
											lowercase__	     =						tokenizer_r.from_pretrained(_UpperCAmelCase						)
											lowercase__	     =						tokenizer_p.from_pretrained(_UpperCAmelCase						)

											# Check special tokens are set accordingly on Rust and Python
											for key in tokenizer_pp.special_tokens_map:
													self.assertTrue(hasattr(_UpperCAmelCase ,   _UpperCAmelCase						)						)
													# self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
													# self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

											shutil.rmtree(_UpperCAmelCase						)

											# Save tokenizer rust, legacy_format=True
											lowercase__	     =						tempfile.mkdtemp()

											lowercase__	     =						tokenizer_r.save_pretrained(_UpperCAmelCase ,   legacy_format=_UpperCAmelCase						)
											lowercase__	     =						tokenizer_p.save_pretrained(_UpperCAmelCase						)

											# Checks it save with the same files
											self.assertSequenceEqual(_UpperCAmelCase ,   _UpperCAmelCase						)

											# Checks everything loads correctly in the same way
											lowercase__	     =						tokenizer_r.from_pretrained(_UpperCAmelCase						)
											lowercase__	     =						tokenizer_p.from_pretrained(_UpperCAmelCase						)

											# Check special tokens are set accordingly on Rust and Python
											for key in tokenizer_pp.special_tokens_map:
													self.assertTrue(hasattr(_UpperCAmelCase ,   _UpperCAmelCase						)						)

											shutil.rmtree(_UpperCAmelCase						)

											# Save tokenizer rust, legacy_format=False
											lowercase__	     =						tempfile.mkdtemp()

											lowercase__	     =						tokenizer_r.save_pretrained(_UpperCAmelCase ,   legacy_format=_UpperCAmelCase						)
											lowercase__	     =						tokenizer_p.save_pretrained(_UpperCAmelCase						)

											# Checks it saved the tokenizer.json file
											self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files						)						)

											# Checks everything loads correctly in the same way
											lowercase__	     =						tokenizer_r.from_pretrained(_UpperCAmelCase						)
											lowercase__	     =						tokenizer_p.from_pretrained(_UpperCAmelCase						)

											# Check special tokens are set accordingly on Rust and Python
											for key in tokenizer_pp.special_tokens_map:
													self.assertTrue(hasattr(_UpperCAmelCase ,   _UpperCAmelCase						)						)

											shutil.rmtree(_UpperCAmelCase						)

					@cached_property
					def     lowerCamelCase__	(self       :		str						)		->  str:




							"""simple docstring"""


							return XLMRobertaTokenizer.from_pretrained("""xlm-roberta-base"""						)

					def     lowerCamelCase__	(self       :		int						)		->  List[str]:




							"""simple docstring"""


							with tempfile.NamedTemporaryFile() as f:
									shutil.copyfile(_UpperCAmelCase ,   f.name						)
									lowercase__	     =						XLMRobertaTokenizer(f.name ,   keep_accents=_UpperCAmelCase						)
									lowercase__	     =						pickle.dumps(_UpperCAmelCase						)
							pickle.loads(_UpperCAmelCase						)

					def     lowerCamelCase__	(self       :		Optional[int]						)		->  Any:




							"""simple docstring"""


							if not self.test_rust_tokenizer:
									return

							lowercase__	     =						self.get_tokenizer()
							lowercase__	     =						self.get_rust_tokenizer()

							lowercase__	     =						"""I was born in 92000, and this is falsé."""

							lowercase__	     =						tokenizer.tokenize(_UpperCAmelCase						)
							lowercase__	     =						rust_tokenizer.tokenize(_UpperCAmelCase						)
							self.assertListEqual(_UpperCAmelCase ,   _UpperCAmelCase						)

							lowercase__	     =						tokenizer.encode(_UpperCAmelCase ,   add_special_tokens=_UpperCAmelCase						)
							lowercase__	     =						rust_tokenizer.encode(_UpperCAmelCase ,   add_special_tokens=_UpperCAmelCase						)
							self.assertListEqual(_UpperCAmelCase ,   _UpperCAmelCase						)

							lowercase__	     =						self.get_rust_tokenizer()
							lowercase__	     =						tokenizer.encode(_UpperCAmelCase						)
							lowercase__	     =						rust_tokenizer.encode(_UpperCAmelCase						)
							self.assertListEqual(_UpperCAmelCase ,   _UpperCAmelCase						)

					@slow
					def     lowerCamelCase__	(self       :		Any						)		->  Union[str, Any]:




							"""simple docstring"""


							lowercase__	     =						"""Hello World!"""
							lowercase__	     =						[0, 3_5378, 6661, 38, 2]
							# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')  # xlmr.large has same tokenizer
							# xlmr.eval()
							# xlmr.encode(symbols)

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

					@slow
					def     lowerCamelCase__	(self       :		str						)		->  Any:




							"""simple docstring"""


							lowercase__	     =						(
							    """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"""
							)
							lowercase__	     =						[
							    0,
							    3293,
							    83,
							    10,
							    4552,
							    4989,
							    7986,
							    678,
							    10,
							    5915,
							    111,
							    17_9459,
							    12_4850,
							    4,
							    6044,
							    237,
							    12,
							    6,
							    5,
							    6,
							    4,
							    6780,
							    705,
							    15,
							    1388,
							    44,
							    378,
							    1_0114,
							    711,
							    152,
							    20,
							    6,
							    5,
							    2_2376,
							    642,
							    1221,
							    1_5190,
							    3_4153,
							    450,
							    5608,
							    959,
							    1119,
							    5_7702,
							    136,
							    186,
							    47,
							    1098,
							    2_9367,
							    47,
							    # 4426, # What fairseq tokenizes from "<unk>": "_<"
							    # 3678, # What fairseq tokenizes from "<unk>": "unk"
							    # 2740, # What fairseq tokenizes from "<unk>": ">"
							    3,  # What we tokenize from "<unk>": "<unk>"
							    6,  # Residue from the tokenization: an extra sentencepiece underline
							    4,
							    6044,
							    237,
							    6284,
							    5_0901,
							    528,
							    31,
							    90,
							    34,
							    927,
							    2,
							]
							# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')  # xlmr.large has same tokenizer
							# xlmr.eval()
							# xlmr.encode(symbols)

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


					@slow
					def     lowerCamelCase__	(self       :		str						)		->  List[str]:




							"""simple docstring"""


							lowercase__	     =						{"""input_ids""": [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 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], [0, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 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]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
							# fmt: on

							self.tokenizer_integration_test_util(
							    expected_encoding=_UpperCAmelCase ,   model_name="""xlm-roberta-base""" ,   revision="""d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3""" ,   )









"""simple docstring"""



import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
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 import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer




class 			lowerCAmelCase__			:
   def __init__(		self      :	Any							,			snake_case__      :	List[str]							,			snake_case__      :	Union[str, Any]=1_3							,			snake_case__      :	Dict=7							,			snake_case__      :	Optional[int]=True							,			snake_case__      :	Optional[int]=True							,			snake_case__      :	int=False							,			snake_case__      :	Optional[Any]=True							,			snake_case__      :	Optional[int]=9_9							,			snake_case__      :	List[Any]=3_2							,			snake_case__      :	Optional[Any]=5							,			snake_case__      :	Union[str, Any]=4							,			snake_case__      :	List[Any]=3_7							,			snake_case__      :	List[str]="gelu"							,			snake_case__      :	List[Any]=0.1							,			snake_case__      :	Tuple=0.1							,			snake_case__      :	Optional[Any]=5_1_2							,			snake_case__      :	Tuple=1_6							,			snake_case__      :	str=2							,			snake_case__      :	Optional[int]=0.02							,			snake_case__      :	int=3							,			snake_case__      :	Union[str, Any]=4							,			snake_case__      :	Optional[int]=None							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							parent
        UpperCAmelCase__						:    Optional[Any]							=							batch_size
        UpperCAmelCase__						:    Any							=							seq_length
        UpperCAmelCase__						:    int							=							is_training
        UpperCAmelCase__						:    Dict							=							use_input_mask
        UpperCAmelCase__						:    List[Any]							=							use_token_type_ids
        UpperCAmelCase__						:    Union[str, Any]							=							use_labels
        UpperCAmelCase__						:    Union[str, Any]							=							vocab_size
        UpperCAmelCase__						:    Union[str, Any]							=							hidden_size
        UpperCAmelCase__						:    Union[str, Any]							=							num_hidden_layers
        UpperCAmelCase__						:    str							=							num_attention_heads
        UpperCAmelCase__						:    int							=							intermediate_size
        UpperCAmelCase__						:    int							=							hidden_act
        UpperCAmelCase__						:    str							=							hidden_dropout_prob
        UpperCAmelCase__						:    Optional[int]							=							attention_probs_dropout_prob
        UpperCAmelCase__						:    List[Any]							=							max_position_embeddings
        UpperCAmelCase__						:    str							=							type_vocab_size
        UpperCAmelCase__						:    Union[str, Any]							=							type_sequence_label_size
        UpperCAmelCase__						:    str							=							initializer_range
        UpperCAmelCase__						:    Tuple							=							num_labels
        UpperCAmelCase__						:    Union[str, Any]							=							num_choices
        UpperCAmelCase__						:    Tuple							=							scope
   def       __a							(		self      :	Tuple							):


        '''simple docstring'''
        UpperCAmelCase__						:    Union[str, Any]							=							ids_tensor([self.batch_size, self.seq_length]							,			self.vocab_size							)

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

        UpperCAmelCase__						:    Dict							=							None
        if self.use_token_type_ids:
             UpperCAmelCase__						:    Optional[int]							=							ids_tensor([self.batch_size, self.seq_length]							,			self.type_vocab_size							)

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

        UpperCAmelCase__						:    Dict							=							self.get_config()

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
   def       __a							(		self      :	Tuple							):


        '''simple docstring'''
        return LlamaConfig(
            vocab_size=self.vocab_size							,			hidden_size=self.hidden_size							,			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							,			is_decoder=snake_case__							,			initializer_range=self.initializer_range							,			)
   def       __a							(		self      :	Optional[int]							,			snake_case__      :	Optional[int]							,			snake_case__      :	Optional[int]							,			snake_case__      :	Tuple							,			snake_case__      :	Dict							,			snake_case__      :	Tuple							,			snake_case__      :	List[str]							,			snake_case__      :	Union[str, Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Optional[Any]							=							LlamaModel(config=snake_case__							)
        model.to(snake_case__							)
        model.eval()
        UpperCAmelCase__						:    List[str]							=							model(snake_case__							,			attention_mask=snake_case__							)
        UpperCAmelCase__						:    Any							=							model(snake_case__							)
        self.parent.assertEqual(result.last_hidden_state.shape							,			(self.batch_size, self.seq_length, self.hidden_size)							)
   def       __a							(		self      :	Any							,			snake_case__      :	Union[str, Any]							,			snake_case__      :	Optional[Any]							,			snake_case__      :	List[Any]							,			snake_case__      :	Dict							,			snake_case__      :	Optional[int]							,			snake_case__      :	Tuple							,			snake_case__      :	Tuple							,			snake_case__      :	str							,			snake_case__      :	int							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    List[Any]							=							True
        UpperCAmelCase__						:    str							=							LlamaModel(snake_case__							)
        model.to(snake_case__							)
        model.eval()
        UpperCAmelCase__						:    Optional[Any]							=							model(
            snake_case__							,			attention_mask=snake_case__							,			encoder_hidden_states=snake_case__							,			encoder_attention_mask=snake_case__							,			)
        UpperCAmelCase__						:    str							=							model(
            snake_case__							,			attention_mask=snake_case__							,			encoder_hidden_states=snake_case__							,			)
        UpperCAmelCase__						:    List[str]							=							model(snake_case__							,			attention_mask=snake_case__							)
        self.parent.assertEqual(result.last_hidden_state.shape							,			(self.batch_size, self.seq_length, self.hidden_size)							)
   def       __a							(		self      :	List[str]							,			snake_case__      :	Dict							,			snake_case__      :	Optional[int]							,			snake_case__      :	int							,			snake_case__      :	Optional[int]							,			snake_case__      :	List[str]							,			snake_case__      :	Optional[int]							,			snake_case__      :	List[Any]							,			snake_case__      :	List[str]							,			snake_case__      :	Union[str, Any]							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    Optional[int]							=							LlamaForCausalLM(config=snake_case__							)
        model.to(snake_case__							)
        model.eval()
        UpperCAmelCase__						:    Optional[Any]							=							model(snake_case__							,			attention_mask=snake_case__							,			labels=snake_case__							)
        self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.seq_length, self.vocab_size)							)
   def       __a							(		self      :	List[str]							,			snake_case__      :	Union[str, Any]							,			snake_case__      :	List[Any]							,			snake_case__      :	int							,			snake_case__      :	Optional[int]							,			snake_case__      :	List[Any]							,			snake_case__      :	int							,			snake_case__      :	Optional[Any]							,			snake_case__      :	Dict							,			snake_case__      :	Optional[int]							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							True
        UpperCAmelCase__						:    str							=							True
        UpperCAmelCase__						:    Union[str, Any]							=							LlamaForCausalLM(config=snake_case__							)
        model.to(snake_case__							)
        model.eval()

        # first forward pass
        UpperCAmelCase__						:    List[str]							=							model(
            snake_case__							,			attention_mask=snake_case__							,			encoder_hidden_states=snake_case__							,			encoder_attention_mask=snake_case__							,			use_cache=snake_case__							,			)
        UpperCAmelCase__						:    Optional[Any]							=							outputs.past_key_values

        # create hypothetical multiple next token and extent to next_input_ids
        UpperCAmelCase__						:    Any							=							ids_tensor((self.batch_size, 3)							,			config.vocab_size							)
        UpperCAmelCase__						:    Optional[int]							=							ids_tensor((self.batch_size, 3)							,			vocab_size=2							)

        # append to next input_ids and
        UpperCAmelCase__						:    str							=							torch.cat([input_ids, next_tokens]							,			dim=-1							)
        UpperCAmelCase__						:    List[Any]							=							torch.cat([input_mask, next_mask]							,			dim=-1							)

        UpperCAmelCase__						:    str							=							model(
            snake_case__							,			attention_mask=snake_case__							,			encoder_hidden_states=snake_case__							,			encoder_attention_mask=snake_case__							,			output_hidden_states=snake_case__							,			)["hidden_states"][0]
        UpperCAmelCase__						:    str							=							model(
            snake_case__							,			attention_mask=snake_case__							,			encoder_hidden_states=snake_case__							,			encoder_attention_mask=snake_case__							,			past_key_values=snake_case__							,			output_hidden_states=snake_case__							,			)["hidden_states"][0]

        # select random slice
        UpperCAmelCase__						:    Dict							=							ids_tensor((1,)							,			output_from_past.shape[-1]							).item()
        UpperCAmelCase__						:    str							=							output_from_no_past[:, -3:, random_slice_idx].detach()
        UpperCAmelCase__						:    Any							=							output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]							)

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(snake_case__							,			snake_case__							,			atol=1e-3							)							)




   def       __a							(		self      :	Dict							):


        '''simple docstring'''
        UpperCAmelCase__						:    int							=							self.prepare_config_and_inputs()
        (
            (
            UpperCAmelCase__
        )							,				(
            UpperCAmelCase__
        )							,				(
            UpperCAmelCase__
        )							,				(
            UpperCAmelCase__
        )							,				(
            UpperCAmelCase__
        )							,				(
            UpperCAmelCase__
        )							,				(
            UpperCAmelCase__
        )							,				
        )						:    Optional[Any]							=							config_and_inputs
        UpperCAmelCase__						:    Union[str, Any]							=							{"input_ids": input_ids, "attention_mask": input_mask}
        return config, inputs_dict




@require_torch
class 			lowerCAmelCase__			(    __magic_name__							,						__magic_name__							,						__magic_name__							,						unittest.TestCase   ):
   SCREAMING_SNAKE_CASE_    =(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
   SCREAMING_SNAKE_CASE_    =(LlamaForCausalLM,) if is_torch_available() else ()
   SCREAMING_SNAKE_CASE_    =(
       {
           '''feature-extraction''': LlamaModel,
           '''text-classification''': LlamaForSequenceClassification,
           '''text-generation''': LlamaForCausalLM,
           '''zero-shot''': LlamaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   SCREAMING_SNAKE_CASE_    =False
   SCREAMING_SNAKE_CASE_    =False
   def       __a							(		self      :	int							):


        '''simple docstring'''
        UpperCAmelCase__						:    Optional[int]							=							LlamaModelTester(self							)
        UpperCAmelCase__						:    str							=							ConfigTester(self							,			config_class=snake_case__							,			hidden_size=3_7							)
   def       __a							(		self      :	Union[str, Any]							):


        '''simple docstring'''
        self.config_tester.run_common_tests()
   def       __a							(		self      :	Dict							):


        '''simple docstring'''
        UpperCAmelCase__						:    Union[str, Any]							=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case__							)
   def       __a							(		self      :	Optional[Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Union[str, Any]							=							self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
             UpperCAmelCase__						:    List[Any]							=							type
             self.model_tester.create_and_check_model(*snake_case__							)
   def       __a							(		self      :	Union[str, Any]							):


        '''simple docstring'''
        UpperCAmelCase__							,				UpperCAmelCase__						:    Tuple							=							self.model_tester.prepare_config_and_inputs_for_common()
        UpperCAmelCase__						:    str							=							3
        UpperCAmelCase__						:    Any							=							input_dict["input_ids"]
        UpperCAmelCase__						:    Any							=							input_ids.ne(1							).to(snake_case__							)
        UpperCAmelCase__						:    str							=							ids_tensor([self.model_tester.batch_size]							,			self.model_tester.type_sequence_label_size							)
        UpperCAmelCase__						:    Optional[Any]							=							LlamaForSequenceClassification(snake_case__							)
        model.to(snake_case__							)
        model.eval()
        UpperCAmelCase__						:    Optional[int]							=							model(snake_case__							,			attention_mask=snake_case__							,			labels=snake_case__							)
        self.assertEqual(result.logits.shape							,			(self.model_tester.batch_size, self.model_tester.num_labels)							)
   def       __a							(		self      :	Optional[int]							):


        '''simple docstring'''
        UpperCAmelCase__							,				UpperCAmelCase__						:    Optional[Any]							=							self.model_tester.prepare_config_and_inputs_for_common()
        UpperCAmelCase__						:    List[Any]							=							3
        UpperCAmelCase__						:    Any							=							"single_label_classification"
        UpperCAmelCase__						:    Tuple							=							input_dict["input_ids"]
        UpperCAmelCase__						:    str							=							input_ids.ne(1							).to(snake_case__							)
        UpperCAmelCase__						:    List[Any]							=							ids_tensor([self.model_tester.batch_size]							,			self.model_tester.type_sequence_label_size							)
        UpperCAmelCase__						:    Any							=							LlamaForSequenceClassification(snake_case__							)
        model.to(snake_case__							)
        model.eval()
        UpperCAmelCase__						:    List[str]							=							model(snake_case__							,			attention_mask=snake_case__							,			labels=snake_case__							)
        self.assertEqual(result.logits.shape							,			(self.model_tester.batch_size, self.model_tester.num_labels)							)
   def       __a							(		self      :	Union[str, Any]							):


        '''simple docstring'''
        UpperCAmelCase__							,				UpperCAmelCase__						:    str							=							self.model_tester.prepare_config_and_inputs_for_common()
        UpperCAmelCase__						:    Dict							=							3
        UpperCAmelCase__						:    Tuple							=							"multi_label_classification"
        UpperCAmelCase__						:    Any							=							input_dict["input_ids"]
        UpperCAmelCase__						:    str							=							input_ids.ne(1							).to(snake_case__							)
        UpperCAmelCase__						:    Any							=							ids_tensor(
            [self.model_tester.batch_size, config.num_labels]							,			self.model_tester.type_sequence_label_size							).to(torch.float							)
        UpperCAmelCase__						:    Dict							=							LlamaForSequenceClassification(snake_case__							)
        model.to(snake_case__							)
        model.eval()
        UpperCAmelCase__						:    int							=							model(snake_case__							,			attention_mask=snake_case__							,			labels=snake_case__							)
        self.assertEqual(result.logits.shape							,			(self.model_tester.batch_size, self.model_tester.num_labels)							)
   @unittest.skip("LLaMA buffers include complex numbers, which breaks this test"							)
   def       __a							(		self      :	str							):


        '''simple docstring'''
        pass




   @parameterized.expand([("linear",), ("dynamic",)]							)
   def       __a							(		self      :	List[str]							,			snake_case__      :	int							):


        '''simple docstring'''
        UpperCAmelCase__							,				UpperCAmelCase__						:    str							=							self.model_tester.prepare_config_and_inputs_for_common()
        UpperCAmelCase__						:    List[str]							=							ids_tensor([1, 1_0]							,			config.vocab_size							)
        UpperCAmelCase__						:    int							=							ids_tensor([1, int(config.max_position_embeddings * 1.5							)]							,			config.vocab_size							)

        set_seed(4_2							)  # Fixed seed at init time so the two models get the same random weights
        UpperCAmelCase__						:    str							=							LlamaModel(snake_case__							)
        original_model.to(snake_case__							)
        original_model.eval()
        UpperCAmelCase__						:    List[Any]							=							original_model(snake_case__							).last_hidden_state
        UpperCAmelCase__						:    Tuple							=							original_model(snake_case__							).last_hidden_state

        set_seed(4_2							)  # Fixed seed at init time so the two models get the same random weights
        UpperCAmelCase__						:    str							=							{"type": scaling_type, "factor": 10.0}
        UpperCAmelCase__						:    Optional[int]							=							LlamaModel(snake_case__							)
        scaled_model.to(snake_case__							)
        scaled_model.eval()
        UpperCAmelCase__						:    Tuple							=							scaled_model(snake_case__							).last_hidden_state
        UpperCAmelCase__						:    Union[str, Any]							=							scaled_model(snake_case__							).last_hidden_state

        # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
        # maximum sequence length, so the outputs for the short input should match.
        if scaling_type == "dynamic":
             self.assertTrue(torch.allclose(snake_case__							,			snake_case__							,			atol=1e-5							)							)
        else:
             self.assertFalse(torch.allclose(snake_case__							,			snake_case__							,			atol=1e-5							)							)

        # The output should be different for long inputs
        self.assertFalse(torch.allclose(snake_case__							,			snake_case__							,			atol=1e-5							)							)




@require_torch
class 			lowerCAmelCase__			(    unittest.TestCase   ):
   @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"							)
   @slow
   def       __a							(		self      :	List[str]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Union[str, Any]							=							[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
        UpperCAmelCase__						:    Any							=							LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf"							,			device_map="auto"							)
        UpperCAmelCase__						:    Any							=							model(torch.tensor([input_ids]							)							)
        # Expected mean on dim = -1
        UpperCAmelCase__						:    Optional[Any]							=							torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]]							)
        torch.testing.assert_close(out.mean(-1							)							,			snake_case__							,			atol=1e-2							,			rtol=1e-2							)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        UpperCAmelCase__						:    Optional[int]							=							torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,]							)
        # fmt: on
        torch.testing.assert_close(out[0, 0, :3_0]							,			snake_case__							,			atol=1e-5							,			rtol=1e-5							)
   @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"							)
   @slow
   def       __a							(		self      :	Any							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
        UpperCAmelCase__						:    Dict							=							LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-hf"							,			device_map="auto"							)
        UpperCAmelCase__						:    List[str]							=							model(torch.tensor(snake_case__							)							)
        # Expected mean on dim = -1
        UpperCAmelCase__						:    str							=							torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]]							)
        torch.testing.assert_close(out.mean(-1							)							,			snake_case__							,			atol=1e-2							,			rtol=1e-2							)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        UpperCAmelCase__						:    str							=							torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273]							)
        # fmt: on
        torch.testing.assert_close(out[0, 0, :3_0]							,			snake_case__							,			atol=1e-5							,			rtol=1e-5							)
   @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"							)
   @slow
   def       __a							(		self      :	int							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[Any]							=							[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
        UpperCAmelCase__						:    Optional[Any]							=							LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf"							,			device_map="auto"							)
        UpperCAmelCase__						:    Dict							=							model(torch.tensor(snake_case__							)							)
        # Expected mean on dim = -1
        UpperCAmelCase__						:    List[str]							=							torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]]							)
        torch.testing.assert_close(out.mean(-1							)							,			snake_case__							,			atol=1e-2							,			rtol=1e-2							)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        UpperCAmelCase__						:    str							=							torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513]							)
        # fmt: on
        torch.testing.assert_close(out.mean(-1							)							,			snake_case__							,			atol=1e-2							,			rtol=1e-2							)
   @unittest.skip(
       "Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test"							)
   @slow
   def       __a							(		self      :	Any							):


        '''simple docstring'''
        UpperCAmelCase__						:    Tuple							=							[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
        UpperCAmelCase__						:    Optional[int]							=							LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-70b-hf"							,			device_map="auto"							)
        UpperCAmelCase__						:    List[Any]							=							model(torch.tensor(snake_case__							)							)

        UpperCAmelCase__						:    str							=							torch.tensor(
            [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]]							,			dtype=torch.floataa							)
        torch.testing.assert_close(out.mean(-1							)							,			snake_case__							,			atol=1e-2							,			rtol=1e-2							)
        # fmt: off
        UpperCAmelCase__						:    Any							=							torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312]							)
        # fmt: on
        torch.testing.assert_close(out[0, 0, :3_0]							,			snake_case__							,			atol=1e-5							,			rtol=1e-5							)




   @unittest.skip("Model is curently gated"							)
   @slow
   def       __a							(		self      :	Dict							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							"Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi"
        UpperCAmelCase__						:    Any							=							"Simply put, the theory of relativity states that "
        UpperCAmelCase__						:    int							=							LlamaTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf"							)
        UpperCAmelCase__						:    List[Any]							=							tokenizer.encode(snake_case__							,			return_tensors="pt"							)
        UpperCAmelCase__						:    Union[str, Any]							=							LlamaForCausalLM.from_pretrained(
            "meta-llama/Llama-2-13b-chat-hf"							,			device_map="sequential"							,			use_safetensors=snake_case__							)

        # greedy generation outputs
        UpperCAmelCase__						:    Optional[int]							=							model.generate(snake_case__							,			max_new_tokens=6_4							,			top_p=snake_case__							,			temperature=1							,			do_sample=snake_case__							)
        UpperCAmelCase__						:    Tuple							=							tokenizer.decode(generated_ids[0]							,			skip_special_tokens=snake_case__							)
        self.assertEqual(snake_case__							,			snake_case__							)


