






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"""




				lowercase__											=			GPTaTokenizer
				lowercase__											=			GPTaTokenizerFast
				lowercase__											=			True
				lowercase__											=			{"""add_prefix_space""": True}
				lowercase__											=			False




				def 							lowercase__  (	self		:       Optional[Any]    ):

								'''simple docstring'''
								super().setUp()

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

								lowercase__  					=     os.path.join(self.tmpdirname,    VOCAB_FILES_NAMES['''vocab_file''']    )
								lowercase__  					=     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(lowerCamelCase    ) + '''\n'''    )
								with open(self.merges_file,    '''w''',    encoding='''utf-8'''    ) as fp:
												fp.write('''\n'''.join(lowerCamelCase    )    )




				def 							lowercase__  (	self		:       Tuple,    **lowerCamelCase		:       List[Any]    ):

								'''simple docstring'''
								kwargs.update(self.special_tokens_map    )
								return GPTaTokenizer.from_pretrained(self.tmpdirname,    **lowerCamelCase    )




				def 							lowercase__  (	self		:       str,    **lowerCamelCase		:       int    ):

								'''simple docstring'''
								kwargs.update(self.special_tokens_map    )
								return GPTaTokenizerFast.from_pretrained(self.tmpdirname,    **lowerCamelCase    )




				def 							lowercase__  (	self		:       Optional[int],    lowerCamelCase		:       Dict    ):

								'''simple docstring'''
								lowercase__  					=     '''lower newer'''
								lowercase__  					=     '''lower newer'''
								return input_text, output_text




				def 							lowercase__  (	self		:       Tuple    ):

								'''simple docstring'''
								lowercase__  					=     GPTaTokenizer(self.vocab_file,    self.merges_file,    **self.special_tokens_map    )
								lowercase__  					=     '''lower newer'''
								lowercase__  					=     ['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
								lowercase__  					=     tokenizer.tokenize(lowerCamelCase,    add_prefix_space=lowerCamelCase    )
								self.assertListEqual(lowerCamelCase,    lowerCamelCase    )

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




				def 							lowercase__  (	self		:       Optional[Any]    ):

								'''simple docstring'''
								if not self.test_rust_tokenizer:
												return

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

								lowercase__  					=     '''lower newer'''

								# Testing tokenization
								lowercase__  					=     tokenizer.tokenize(lowerCamelCase,    add_prefix_space=lowerCamelCase    )
								lowercase__  					=     rust_tokenizer.tokenize(lowerCamelCase    )
								self.assertListEqual(lowerCamelCase,    lowerCamelCase    )

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

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

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




				def 							lowercase__  (	self		:       Union[str, Any],    *lowerCamelCase		:       Optional[int],    **lowerCamelCase		:       Any    ):

								'''simple docstring'''
								# 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 							lowercase__  (	self		:       Any,    lowerCamelCase		:       str=15    ):

								'''simple docstring'''
								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(lowerCamelCase,    **lowerCamelCase    )

																# Simple input
																lowercase__  					=     '''This is a simple input'''
																lowercase__  					=     ['''This is a simple input 1''', '''This is a simple input 2''']
																lowercase__  					=     ('''This is a simple input''', '''This is a pair''')
																lowercase__  					=     [
																    ('''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(lowerCamelCase,    tokenizer_r.encode,    lowerCamelCase,    max_length=lowerCamelCase,    padding='''max_length'''    )

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

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

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

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

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




				def 							lowercase__  (	self		:       Optional[Any]    ):

								'''simple docstring'''
								lowercase__  					=     GPTaTokenizer.from_pretrained(self.tmpdirname,    pad_token='''<pad>'''    )

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

								lowercase__  					=     tokenizer.pad_token_id

								lowercase__  					=     tokenizer(lowerCamelCase,    padding='''max_length''',    max_length=30,    return_tensors='''np'''    )
								lowercase__  					=     tokenizer(lowerCamelCase,    padding=lowerCamelCase,    truncate=lowerCamelCase,    return_tensors='''np'''    )
								lowercase__  					=     tokenizer(*lowerCamelCase,    padding='''max_length''',    max_length=60,    return_tensors='''np'''    )
								lowercase__  					=     tokenizer(lowerCamelCase,    padding=lowerCamelCase,    truncate=lowerCamelCase,    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 							lowercase__  (	self		:       str    ):

								'''simple docstring'''
								lowercase__  					=     '''$$$'''
								lowercase__  					=     GPTaTokenizer.from_pretrained(self.tmpdirname,    bos_token=lowerCamelCase,    add_bos_token=lowerCamelCase    )

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

								lowercase__  					=     tokenizer.bos_token_id

								lowercase__  					=     tokenizer(lowerCamelCase    )
								lowercase__  					=     tokenizer(lowerCamelCase    )

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

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

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




				def 							lowercase__  (	self		:       Any    ):

								'''simple docstring'''
								pass




				def 							lowercase__  (	self		:       Optional[int]    ):

								'''simple docstring'''
								# TODO: change to self.get_tokenizers() when the fast version is implemented
								lowercase__  					=     [self.get_tokenizer(do_lower_case=lowerCamelCase,    add_bos_token=lowerCamelCase    )]
								for tokenizer in tokenizers:
												with self.subTest(F"""{tokenizer.__class__.__name__}"""    ):
																lowercase__  					=     '''Encode this.'''
																lowercase__  					=     '''This one too please.'''
																lowercase__  					=     tokenizer.encode(lowerCamelCase,    add_special_tokens=lowerCamelCase    )
																encoded_sequence += tokenizer.encode(lowerCamelCase,    add_special_tokens=lowerCamelCase    )
																lowercase__  					=     tokenizer.encode_plus(
																    lowerCamelCase,    lowerCamelCase,    add_special_tokens=lowerCamelCase,    return_special_tokens_mask=lowerCamelCase,    )
																lowercase__  					=     encoded_sequence_dict['''input_ids''']
																lowercase__  					=     encoded_sequence_dict['''special_tokens_mask''']
																self.assertEqual(len(lowerCamelCase    ),    len(lowerCamelCase    )    )

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



@require_tokenizers
class  _UpperCAmelCase   (			unittest.TestCase      ):

				"""simple docstring"""




				def 							lowercase__  (	self		:       Tuple    ):

								'''simple docstring'''
								# 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

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

								lowercase__  					=     tokenizer.encode(
								    lowerCamelCase,    )
								self.assertEqual(lowerCamelCase,    [2, 250, 1_345, 9, 10, 4_758]    )
								tokenizer.save_pretrained('''test_opt'''    )

								lowercase__  					=     AutoTokenizer.from_pretrained('''./test_opt'''    )
								lowercase__  					=     tokenizer.encode(
								    lowerCamelCase,    )
								self.assertEqual(lowerCamelCase,    [2, 250, 1_345, 9, 10, 4_758]    )




				def 							lowercase__  (	self		:       Optional[Any]    ):

								'''simple docstring'''
								lowercase__  					=     AutoTokenizer.from_pretrained('''facebook/opt-350m''',    use_slow=lowerCamelCase    )
								lowercase__  					=     '''A photo of a cat'''

								lowercase__  					=     tokenizer.encode(
								    lowerCamelCase,    )
								# Same as above
								self.assertEqual(lowerCamelCase,    [2, 250, 1_345, 9, 10, 4_758]    )




				@unittest.skip('''This test is failing because of a bug in the fast tokenizer'''    )
				def 							lowercase__  (	self		:       Union[str, Any]    ):

								'''simple docstring'''
								lowercase__  					=     AutoTokenizer.from_pretrained('''facebook/opt-350m''',    from_slow=lowerCamelCase    )

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

								lowercase__  					=     '''A photo of a cat'''
								lowercase__  					=     tokenizer.encode(
								    lowerCamelCase,    )
								# We changed the bos token
								self.assertEqual(lowerCamelCase,    [31_957, 250, 1_345, 9, 10, 4_758]    )
								tokenizer.save_pretrained('''./tok'''    )
								lowercase__  					=     AutoTokenizer.from_pretrained('''./tok'''    )
								self.assertTrue(tokenizer.is_fast    )
								lowercase__  					=     tokenizer.encode(
								    lowerCamelCase,    )
								self.assertEqual(lowerCamelCase,    [31_957, 250, 1_345, 9, 10, 4_758]    )












import unittest

import numpy as np

from transformers import RobertaPreLayerNormConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
							import jax.numpy as jnp

							from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import (
							    FlaxRobertaPreLayerNormForCausalLM,
							    FlaxRobertaPreLayerNormForMaskedLM,
							    FlaxRobertaPreLayerNormForMultipleChoice,
							    FlaxRobertaPreLayerNormForQuestionAnswering,
							    FlaxRobertaPreLayerNormForSequenceClassification,
							    FlaxRobertaPreLayerNormForTokenClassification,
							    FlaxRobertaPreLayerNormModel,
							)
class  _UpperCAmelCase   (			unittest.TestCase      ):

				"""simple docstring"""




				def __init__(	self		:       List[Any],    lowerCamelCase		:       Dict,    lowerCamelCase		:       Dict=13,    lowerCamelCase		:       Optional[int]=7,    lowerCamelCase		:       Optional[Any]=True,    lowerCamelCase		:       Union[str, Any]=True,    lowerCamelCase		:       Optional[Any]=True,    lowerCamelCase		:       Optional[Any]=True,    lowerCamelCase		:       List[Any]=99,    lowerCamelCase		:       Any=32,    lowerCamelCase		:       List[str]=5,    lowerCamelCase		:       Union[str, Any]=4,    lowerCamelCase		:       Union[str, Any]=37,    lowerCamelCase		:       Optional[int]="gelu",    lowerCamelCase		:       Tuple=0.1,    lowerCamelCase		:       List[str]=0.1,    lowerCamelCase		:       Optional[Any]=512,    lowerCamelCase		:       int=16,    lowerCamelCase		:       str=2,    lowerCamelCase		:       int=0.02,    lowerCamelCase		:       int=4,    ):

								'''simple docstring'''
								lowercase__  					=     parent
								lowercase__  					=     batch_size
								lowercase__  					=     seq_length
								lowercase__  					=     is_training
								lowercase__  					=     use_attention_mask
								lowercase__  					=     use_token_type_ids
								lowercase__  					=     use_labels
								lowercase__  					=     vocab_size
								lowercase__  					=     hidden_size
								lowercase__  					=     num_hidden_layers
								lowercase__  					=     num_attention_heads
								lowercase__  					=     intermediate_size
								lowercase__  					=     hidden_act
								lowercase__  					=     hidden_dropout_prob
								lowercase__  					=     attention_probs_dropout_prob
								lowercase__  					=     max_position_embeddings
								lowercase__  					=     type_vocab_size
								lowercase__  					=     type_sequence_label_size
								lowercase__  					=     initializer_range
								lowercase__  					=     num_choices




				def 							lowercase__  (	self		:       Dict    ):

								'''simple docstring'''
								lowercase__  					=     ids_tensor([self.batch_size, self.seq_length],    self.vocab_size    )

								lowercase__  					=     None
								if self.use_attention_mask:
												lowercase__  					=     random_attention_mask([self.batch_size, self.seq_length]    )

								lowercase__  					=     None
								if self.use_token_type_ids:
												lowercase__  					=     ids_tensor([self.batch_size, self.seq_length],    self.type_vocab_size    )

								lowercase__  					=     RobertaPreLayerNormConfig(
								    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=lowerCamelCase,    initializer_range=self.initializer_range,    )

								return config, input_ids, token_type_ids, attention_mask




				def 							lowercase__  (	self		:       List[str]    ):

								'''simple docstring'''
								lowercase__  					=     self.prepare_config_and_inputs()
								lowercase__					,		lowercase__					,		lowercase__					,		lowercase__  					=     config_and_inputs
								lowercase__  					=     {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
								return config, inputs_dict




				def 							lowercase__  (	self		:       Optional[int]    ):

								'''simple docstring'''
								lowercase__  					=     self.prepare_config_and_inputs()
								lowercase__					,		lowercase__					,		lowercase__					,		lowercase__  					=     config_and_inputs

								lowercase__  					=     True
								lowercase__  					=     floats_tensor([self.batch_size, self.seq_length, self.hidden_size]    )
								lowercase__  					=     ids_tensor([self.batch_size, self.seq_length],    vocab_size=2    )

								return (
								    config,
								    input_ids,
								    token_type_ids,
								    encoder_hidden_states,
								    encoder_attention_mask,
								)



@require_flax
# Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40
class  _UpperCAmelCase   (			A__						,unittest.TestCase      ):

				"""simple docstring"""




				lowercase__											=			True

				lowercase__											=			(
				    (
				        FlaxRobertaPreLayerNormModel,
				        FlaxRobertaPreLayerNormForCausalLM,
				        FlaxRobertaPreLayerNormForMaskedLM,
				        FlaxRobertaPreLayerNormForSequenceClassification,
				        FlaxRobertaPreLayerNormForTokenClassification,
				        FlaxRobertaPreLayerNormForMultipleChoice,
				        FlaxRobertaPreLayerNormForQuestionAnswering,
				    )
				    if is_flax_available()
				    else ()
				)




				def 							lowercase__  (	self		:       int    ):

								'''simple docstring'''
								lowercase__  					=     FlaxRobertaPreLayerNormModelTester(self    )




				@slow
				def 							lowercase__  (	self		:       List[Any]    ):

								'''simple docstring'''
								for model_class_name in self.all_model_classes:
												lowercase__  					=     model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''',    from_pt=lowerCamelCase    )
												lowercase__  					=     model(np.ones((1, 1)    )    )
												self.assertIsNotNone(lowerCamelCase    )



@require_flax
class  _UpperCAmelCase   (			unittest.TestCase      ):

				"""simple docstring"""




				@slow
				def 							lowercase__  (	self		:       Union[str, Any]    ):

								'''simple docstring'''
								lowercase__  					=     FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''',    from_pt=lowerCamelCase    )

								lowercase__  					=     np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]],    dtype=jnp.intaa    )
								lowercase__  					=     model(lowerCamelCase    )[0]
								lowercase__  					=     [1, 11, 50_265]
								self.assertEqual(list(output.shape    ),    lowerCamelCase    )
								# compare the actual values for a slice.
								lowercase__  					=     np.array(
								    [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]],    dtype=np.floataa    )
								self.assertTrue(np.allclose(output[:, :3, :3],    lowerCamelCase,    atol=1E-4    )    )




				@slow
				def 							lowercase__  (	self		:       Any    ):

								'''simple docstring'''
								lowercase__  					=     FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''',    from_pt=lowerCamelCase    )

								lowercase__  					=     np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]],    dtype=jnp.intaa    )
								lowercase__  					=     model(lowerCamelCase    )[0]
								# compare the actual values for a slice.
								lowercase__  					=     np.array(
								    [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]],    dtype=np.floataa    )
								self.assertTrue(np.allclose(output[:, :3, :3],    lowerCamelCase,    atol=1E-4    )    )




