


import json
import os
import unittest

from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast
from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class     UpperCAmelCase__       (					A_   ,  unittest.TestCase		):



    """simple docstring"""






    UpperCAmelCase__						:		Dict      =  GPTaTokenizer
    UpperCAmelCase__						:		Any      =  GPTaTokenizerFast
    UpperCAmelCase__						:		Tuple      =  True
    UpperCAmelCase__						:		int      =  {"add_prefix_space": True}
    UpperCAmelCase__						:		Any      =  False






    def _a					(			self    )  ->       Optional[int]:
         super().setUp()

         # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
         __UpperCamelCase    							=[
             'l',
             'o',
             'w',
             'e',
             'r',
             's',
             't',
             'i',
             'd',
             'n',
             '\u0120',
             '\u0120l',
             '\u0120n',
             '\u0120lo',
             '\u0120low',
             'er',
             '\u0120lowest',
             '\u0120newer',
             '\u0120wider',
             '<unk>',
             '<|endoftext|>',
         ]
         __UpperCamelCase    							=dict(zip(A_					,   range(len(A_    )    )    )    )
         __UpperCamelCase    							=['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
         __UpperCamelCase    							={'unk_token': '<unk>'}

         __UpperCamelCase    							=os.path.join(self.tmpdirname					,   VOCAB_FILES_NAMES['vocab_file']    )
         __UpperCamelCase    							=os.path.join(self.tmpdirname					,   VOCAB_FILES_NAMES['merges_file']    )
         with open(self.vocab_file					,   'w'					,   encoding='utf-8'    ) as fp:
              fp.write(json.dumps(A_    ) + '\n'    )
         with open(self.merges_file					,   'w'					,   encoding='utf-8'    ) as fp:
              fp.write('\n'.join(A_    )    )






    def _a					(			self					,   **A_    )  ->       str:
         kwargs.update(self.special_tokens_map    )
         return GPTaTokenizer.from_pretrained(self.tmpdirname					,   **A_    )






    def _a					(			self					,   **A_    )  ->       Optional[Any]:
         kwargs.update(self.special_tokens_map    )
         return GPTaTokenizerFast.from_pretrained(self.tmpdirname					,   **A_    )






    def _a					(			self					,   A_    )  ->       Tuple:
         __UpperCamelCase    							='lower newer'
         __UpperCamelCase    							='lower newer'
         return input_text, output_text






    def _a					(			self    )  ->       List[Any]:
         __UpperCamelCase    							=GPTaTokenizer(self.vocab_file					,   self.merges_file					,   **self.special_tokens_map    )
         __UpperCamelCase    							='lower newer'
         __UpperCamelCase    							=['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er']
         __UpperCamelCase    							=tokenizer.tokenize(A_					,   add_prefix_space=A_    )
         self.assertListEqual(A_					,   A_    )

         __UpperCamelCase    							=tokens + [tokenizer.unk_token]
         __UpperCamelCase    							=[14, 15, 10, 9, 3, 2, 15, 19]
         self.assertListEqual(tokenizer.convert_tokens_to_ids(A_    )					,   A_    )






    def _a					(			self    )  ->       int:
         if not self.test_rust_tokenizer:
              return

         __UpperCamelCase    							=self.get_tokenizer()
         __UpperCamelCase    							=self.get_rust_tokenizer(add_prefix_space=A_    )

         __UpperCamelCase    							='lower newer'

         # Testing tokenization
         __UpperCamelCase    							=tokenizer.tokenize(A_					,   add_prefix_space=A_    )
         __UpperCamelCase    							=rust_tokenizer.tokenize(A_    )
         self.assertListEqual(A_					,   A_    )

         # Testing conversion to ids without special tokens
         __UpperCamelCase    							=tokenizer.encode(A_					,   add_special_tokens=A_					,   add_prefix_space=A_    )
         __UpperCamelCase    							=rust_tokenizer.encode(A_					,   add_special_tokens=A_    )
         self.assertListEqual(A_					,   A_    )

         # Testing conversion to ids with special tokens
         __UpperCamelCase    							=self.get_rust_tokenizer(add_prefix_space=A_    )
         __UpperCamelCase    							=tokenizer.encode(A_					,   add_prefix_space=A_    )
         __UpperCamelCase    							=rust_tokenizer.encode(A_    )
         self.assertListEqual(A_					,   A_    )

         # Testing the unknown token
         __UpperCamelCase    							=tokens + [rust_tokenizer.unk_token]
         __UpperCamelCase    							=[14, 15, 10, 9, 3, 2, 15, 19]
         self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_    )					,   A_    )






    def _a					(			self					,   *A_					,   **A_    )  ->       Optional[int]:
         # It's very difficult to mix/test pretokenization with byte-level
         # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string)
         pass






    def _a					(			self					,   A_=15    )  ->       List[str]:
         for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
              with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})'    ):
                   __UpperCamelCase    							=self.rust_tokenizer_class.from_pretrained(A_					,   **A_    )

                   # Simple input
                   __UpperCamelCase    							='This is a simple input'
                   __UpperCamelCase    							=['This is a simple input 1', 'This is a simple input 2']
                   __UpperCamelCase    							=('This is a simple input', 'This is a pair')
                   __UpperCamelCase    							=[
                       ('This is a simple input 1', 'This is a simple input 2'),
                       ('This is a simple pair 1', 'This is a simple pair 2'),
                   ]

                   # Simple input tests
                   self.assertRaises(A_					,   tokenizer_r.encode					,   A_					,   max_length=A_					,   padding='max_length'    )

                   # Simple input
                   self.assertRaises(A_					,   tokenizer_r.encode_plus					,   A_					,   max_length=A_					,   padding='max_length'    )

                   # Simple input
                   self.assertRaises(
                       A_					,   tokenizer_r.batch_encode_plus					,   A_					,   max_length=A_					,   padding='max_length'					,   )

                   # Pair input
                   self.assertRaises(A_					,   tokenizer_r.encode					,   A_					,   max_length=A_					,   padding='max_length'    )

                   # Pair input
                   self.assertRaises(A_					,   tokenizer_r.encode_plus					,   A_					,   max_length=A_					,   padding='max_length'    )

                   # Pair input
                   self.assertRaises(
                       A_					,   tokenizer_r.batch_encode_plus					,   A_					,   max_length=A_					,   padding='max_length'					,   )






    def _a					(			self    )  ->       int:
         __UpperCamelCase    							=GPTaTokenizer.from_pretrained(self.tmpdirname					,   pad_token='<pad>'    )

         # Simple input
         __UpperCamelCase    							='This is a simple input'
         __UpperCamelCase    							=['This is a simple input looooooooong', 'This is a simple input']
         __UpperCamelCase    							=('This is a simple input', 'This is a pair')
         __UpperCamelCase    							=[
             ('This is a simple input loooooong', 'This is a simple input'),
             ('This is a simple pair loooooong', 'This is a simple pair'),
         ]

         __UpperCamelCase    							=tokenizer.pad_token_id

         __UpperCamelCase    							=tokenizer(A_					,   padding='max_length'					,   max_length=30					,   return_tensors='np'    )
         __UpperCamelCase    							=tokenizer(A_					,   padding=A_					,   truncate=A_					,   return_tensors='np'    )
         __UpperCamelCase    							=tokenizer(*A_					,   padding='max_length'					,   max_length=60					,   return_tensors='np'    )
         __UpperCamelCase    							=tokenizer(A_					,   padding=A_					,   truncate=A_					,   return_tensors='np'    )

         # s
         # test single string max_length padding
         self.assertEqual(out_s['input_ids'].shape[-1]					,   30    )
         self.assertTrue(pad_token_id in out_s['input_ids']    )
         self.assertTrue(0 in out_s['attention_mask']    )

         # s2
         # test automatic padding
         self.assertEqual(out_sa['input_ids'].shape[-1]					,   33    )
         # long slice doesn't have padding
         self.assertFalse(pad_token_id in out_sa['input_ids'][0]    )
         self.assertFalse(0 in out_sa['attention_mask'][0]    )
         # short slice does have padding
         self.assertTrue(pad_token_id in out_sa['input_ids'][1]    )
         self.assertTrue(0 in out_sa['attention_mask'][1]    )

         # p
         # test single pair max_length padding
         self.assertEqual(out_p['input_ids'].shape[-1]					,   60    )
         self.assertTrue(pad_token_id in out_p['input_ids']    )
         self.assertTrue(0 in out_p['attention_mask']    )

         # p2
         # test automatic padding pair
         self.assertEqual(out_pa['input_ids'].shape[-1]					,   52    )
         # long slice pair doesn't have padding
         self.assertFalse(pad_token_id in out_pa['input_ids'][0]    )
         self.assertFalse(0 in out_pa['attention_mask'][0]    )
         # short slice pair does have padding
         self.assertTrue(pad_token_id in out_pa['input_ids'][1]    )
         self.assertTrue(0 in out_pa['attention_mask'][1]    )






    def _a					(			self    )  ->       Union[str, Any]:
         __UpperCamelCase    							='$$$'
         __UpperCamelCase    							=GPTaTokenizer.from_pretrained(self.tmpdirname					,   bos_token=A_					,   add_bos_token=A_    )

         __UpperCamelCase    							='This is a simple input'
         __UpperCamelCase    							=['This is a simple input 1', 'This is a simple input 2']

         __UpperCamelCase    							=tokenizer.bos_token_id

         __UpperCamelCase    							=tokenizer(A_    )
         __UpperCamelCase    							=tokenizer(A_    )

         self.assertEqual(out_s.input_ids[0]					,   A_    )
         self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids    )    )

         __UpperCamelCase    							=tokenizer.decode(out_s.input_ids    )
         __UpperCamelCase    							=tokenizer.batch_decode(out_sa.input_ids    )

         self.assertEqual(decode_s.split()[0]					,   A_    )
         self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa    )    )






    def _a					(			self    )  ->       Optional[int]:
         pass






    def _a					(			self    )  ->       Any:
         # TODO: change to self.get_tokenizers() when the fast version is implemented
         __UpperCamelCase    							=[self.get_tokenizer(do_lower_case=A_					,   add_bos_token=A_    )]
         for tokenizer in tokenizers:
              with self.subTest(f'{tokenizer.__class__.__name__}'    ):
                   __UpperCamelCase    							='Encode this.'
                   __UpperCamelCase    							='This one too please.'
                   __UpperCamelCase    							=tokenizer.encode(A_					,   add_special_tokens=A_    )
                   encoded_sequence += tokenizer.encode(A_					,   add_special_tokens=A_    )
                   __UpperCamelCase    							=tokenizer.encode_plus(
                       A_					,   A_					,   add_special_tokens=A_					,   return_special_tokens_mask=A_					,   )
                   __UpperCamelCase    							=encoded_sequence_dict['input_ids']
                   __UpperCamelCase    							=encoded_sequence_dict['special_tokens_mask']
                   self.assertEqual(len(A_    )					,   len(A_    )    )

                   __UpperCamelCase    							=[
                       (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_    )
                   ]
                   __UpperCamelCase    							=[x for x in filtered_sequence if x is not None]
                   self.assertEqual(A_					,   A_    )






@require_tokenizers
class     UpperCAmelCase__       (					unittest.TestCase		):



    """simple docstring"""






    def _a					(			self    )  ->       Optional[Any]:
         # More context:
         # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1
         # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519
         # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439

         __UpperCamelCase    							=AutoTokenizer.from_pretrained('facebook/opt-350m'					,   from_slow=A_    )
         __UpperCamelCase    							='A photo of a cat'

         __UpperCamelCase    							=tokenizer.encode(
             A_					,   )
         self.assertEqual(A_					,   [2, 250, 1345, 9, 10, 4758]    )
         tokenizer.save_pretrained('test_opt'    )

         __UpperCamelCase    							=AutoTokenizer.from_pretrained('./test_opt'    )
         __UpperCamelCase    							=tokenizer.encode(
             A_					,   )
         self.assertEqual(A_					,   [2, 250, 1345, 9, 10, 4758]    )






    def _a					(			self    )  ->       Dict:
         __UpperCamelCase    							=AutoTokenizer.from_pretrained('facebook/opt-350m'					,   use_slow=A_    )
         __UpperCamelCase    							='A photo of a cat'

         __UpperCamelCase    							=tokenizer.encode(
             A_					,   )
         # Same as above
         self.assertEqual(A_					,   [2, 250, 1345, 9, 10, 4758]    )






    @unittest.skip('This test is failing because of a bug in the fast tokenizer'    )
    def _a					(			self    )  ->       List[Any]:
         __UpperCamelCase    							=AutoTokenizer.from_pretrained('facebook/opt-350m'					,   from_slow=A_    )

         __UpperCamelCase    							='bos'
         __UpperCamelCase    							=tokenizer.get_vocab()['bos']

         __UpperCamelCase    							='A photo of a cat'
         __UpperCamelCase    							=tokenizer.encode(
             A_					,   )
         # We changed the bos token
         self.assertEqual(A_					,   [31957, 250, 1345, 9, 10, 4758]    )
         tokenizer.save_pretrained('./tok'    )
         __UpperCamelCase    							=AutoTokenizer.from_pretrained('./tok'    )
         self.assertTrue(tokenizer.is_fast    )
         __UpperCamelCase    							=tokenizer.encode(
             A_					,   )
         self.assertEqual(A_					,   [31957, 250, 1345, 9, 10, 4758]    )










from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A__  :  Union[str, Any]								=					logging.get_logger(__name__)

A__  :  Tuple								=					{
    '''facebook/xlm-roberta-xl''': '''https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json''',
    '''facebook/xlm-roberta-xxl''': '''https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json''',
    # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl
}



class 				__snake_case						(     UpperCamelCase_						):
							_a			      = '''xlm-roberta-xl'''




							def __init__(       self     :       int				,				A_     :       List[str]=2_5_0_8_8_0				,				A_     :       List[str]=2_5_6_0				,				A_     :       Optional[int]=3_6				,				A_     :       List[Any]=3_2				,				A_     :       Optional[int]=1_0_2_4_0				,				A_     :       Dict="gelu"				,				A_     :       int=0.1				,				A_     :       Optional[Any]=0.1				,				A_     :       int=5_1_4				,				A_     :       Any=1				,				A_     :       Optional[Any]=0.02				,				A_     :       str=1e-05				,				A_     :       Dict=1				,				A_     :       Any=0				,				A_     :       Tuple=2				,				A_     :       str="absolute"				,				A_     :       str=True				,				A_     :       List[str]=None				,				**A_     :       Dict				,				):
									super().__init__(pad_token_id=A_				,				bos_token_id=A_				,				eos_token_id=A_				,				**A_)
									lowerCAmelCase_			:     Tuple									= vocab_size
									lowerCAmelCase_			:     List[str]									= hidden_size
									lowerCAmelCase_			:     int									= num_hidden_layers
									lowerCAmelCase_			:     int									= num_attention_heads
									lowerCAmelCase_			:     Dict									= hidden_act
									lowerCAmelCase_			:     int									= intermediate_size
									lowerCAmelCase_			:     Tuple									= hidden_dropout_prob
									lowerCAmelCase_			:     Optional[Any]									= attention_probs_dropout_prob
									lowerCAmelCase_			:     Union[str, Any]									= max_position_embeddings
									lowerCAmelCase_			:     Dict									= type_vocab_size
									lowerCAmelCase_			:     str									= initializer_range
									lowerCAmelCase_			:     str									= layer_norm_eps
									lowerCAmelCase_			:     Optional[Any]									= position_embedding_type
									lowerCAmelCase_			:     Optional[Any]									= use_cache
									lowerCAmelCase_			:     List[str]									= classifier_dropout





class 				__snake_case						(     UpperCamelCase_						):




							@property
							def    UpperCAmelCase__			(       self     :       List[str]):
									if self.task == "multiple-choice":
											lowerCAmelCase_			:     Union[str, Any]									= {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
									else:
											lowerCAmelCase_			:     List[Any]									= {0: '''batch''', 1: '''sequence'''}
									return OrderedDict(
									    [
									        ('''input_ids''', dynamic_axis),
									        ('''attention_mask''', dynamic_axis),
									    ])





