






"""simple docstring"""







import json
import os
import re
import unittest

from transformers import CodeGenTokenizer, CodeGenTokenizerFast
from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class        _SCREAMING_SNAKE_CASE						(  __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =CodeGenTokenizer
							_SCREAMING_SNAKE_CASE    =CodeGenTokenizerFast
							_SCREAMING_SNAKE_CASE    =True
							_SCREAMING_SNAKE_CASE    ={'add_prefix_space': True}
							_SCREAMING_SNAKE_CASE    =False




							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												super().setUp()

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

												a__          =  os.path.join(self.tmpdirname				,		VOCAB_FILES_NAMES['''vocab_file''']    )
												a__          =  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  lowercase		(   self:     int				,		**__A:     Optional[Any]    ):

												'''simple docstring'''

												kwargs.update(self.special_tokens_map    )
												return CodeGenTokenizer.from_pretrained(self.tmpdirname				,		**__A    )




							def  lowercase		(   self:     List[Any]				,		**__A:     str    ):

												'''simple docstring'''

												kwargs.update(self.special_tokens_map    )
												return CodeGenTokenizerFast.from_pretrained(self.tmpdirname				,		**__A    )




							def  lowercase		(   self:     Optional[Any]				,		__A:     int    ):

												'''simple docstring'''

												a__          =  '''lower newer'''
												a__          =  '''lower newer'''
												return input_text, output_text




							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												a__          =  CodeGenTokenizer(self.vocab_file				,		self.merges_file				,		**self.special_tokens_map    )
												a__          =  '''lower newer'''
												a__          =  ['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
												a__          =  tokenizer.tokenize(__A				,		add_prefix_space=__A    )
												self.assertListEqual(__A				,		__A    )

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




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												if not self.test_rust_tokenizer:
																	return

												a__          =  self.get_tokenizer()
												a__          =  self.get_rust_tokenizer(add_prefix_space=__A    )

												a__          =  '''lower newer'''

												# Testing tokenization
												a__          =  tokenizer.tokenize(__A				,		add_prefix_space=__A    )
												a__          =  rust_tokenizer.tokenize(__A    )
												self.assertListEqual(__A				,		__A    )

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

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

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




							def  lowercase		(   self:     Union[str, Any]				,		*__A:     List[Any]				,		**__A:     Any    ):

												'''simple docstring'''

												pass




							def  lowercase		(   self:     Dict				,		__A:     Optional[int]=15    ):

												'''simple docstring'''

												for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																	with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'    ):
																						a__          =  self.rust_tokenizer_class.from_pretrained(__A				,		**__A    )

																						# Simple input
																						a__          =  '''This is a simple input'''
																						a__          =  ['''This is a simple input 1''', '''This is a simple input 2''']
																						a__          =  ('''This is a simple input''', '''This is a pair''')
																						a__          =  [
																						    ('''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  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  CodeGenTokenizer.from_pretrained(self.tmpdirname				,		pad_token='''<pad>'''    )

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

												a__          =  tokenizer.pad_token_id

												a__          =  tokenizer(__A				,		padding='''max_length'''				,		max_length=30				,		return_tensors='''np'''    )
												a__          =  tokenizer(__A				,		padding=__A				,		truncate=__A				,		return_tensors='''np'''    )
												a__          =  tokenizer(*__A				,		padding='''max_length'''				,		max_length=60				,		return_tensors='''np'''    )
												a__          =  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  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  '''$$$'''
												a__          =  CodeGenTokenizer.from_pretrained(self.tmpdirname				,		bos_token=__A				,		add_bos_token=__A    )

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

												a__          =  tokenizer.bos_token_id

												a__          =  tokenizer(__A    )
												a__          =  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    )    )

												a__          =  tokenizer.decode(out_s.input_ids    )
												a__          =  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    )    )




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

												'''simple docstring'''

												a__          =  CodeGenTokenizer.from_pretrained('''Salesforce/codegen-350M-mono'''    )

												a__          =  '''\nif len_a > len_b:\n    result = a\nelse:\n    result = b\n\n\n\n#'''
												a__          =  '''\nif len_a > len_b:      result = a\nelse:      result = b'''

												a__          =  tokenizer.encode(__A    )
												a__          =  ['''^#''', re.escape('''<|endoftext|>'''    ), '''^\'\'\'''', '''^"""''', '''\n\n\n''']
												a__          =  tokenizer.decode(__A				,		truncate_before_pattern=__A    )
												self.assertEqual(__A				,		__A    )





							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												pass










"""simple docstring"""







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        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





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

												'''simple docstring'''

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




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  ids_tensor([self.batch_size, self.seq_length]				,		self.vocab_size    )

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

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

												a__          =  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=__A				,		initializer_range=self.initializer_range				,		)

												return config, input_ids, token_type_ids, attention_mask




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

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





							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												a__       ,a__       ,a__       ,a__          =  config_and_inputs

												a__          =  True
												a__          =  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]    )
												a__          =  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        _SCREAMING_SNAKE_CASE						(  __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =True

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




							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												a__          =  FlaxRobertaPreLayerNormModelTester(self    )





							@slow
							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												for model_class_name in self.all_model_classes:
																	a__          =  model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,		from_pt=__A    )
																	a__          =  model(np.ones((1, 1)    )    )
																	self.assertIsNotNone(__A    )







@require_flax
class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							@slow
							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,		from_pt=__A    )

												a__          =  np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]				,		dtype=jnp.intaa    )
												a__          =  model(__A    )[0]
												a__          =  [1, 11, 50265]
												self.assertEqual(list(output.shape    )				,		__A    )
												# compare the actual values for a slice.
												a__          =  np.array(
												    [[[4_0.4_8_8_0, 1_8.0_1_9_9, -5.2_3_6_7], [-1.8_8_7_7, -4.0_8_8_5, 1_0.7_0_8_5], [-2.2_6_1_3, -5.6_1_1_0, 7.2_6_6_5]]]				,		dtype=np.floataa    )
												self.assertTrue(np.allclose(output[:, :3, :3]				,		__A				,		atol=1e-4    )    )





							@slow
							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40'''				,		from_pt=__A    )

												a__          =  np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]				,		dtype=jnp.intaa    )
												a__          =  model(__A    )[0]
												# compare the actual values for a slice.
												a__          =  np.array(
												    [[[0.0_2_0_8, -0.0_3_5_6, 0.0_2_3_7], [-0.1_5_6_9, -0.0_4_1_1, -0.2_6_2_6], [0.1_8_7_9, 0.0_1_2_5, -0.0_0_8_9]]]				,		dtype=np.floataa    )
												self.assertTrue(np.allclose(output[:, :3, :3]				,		__A				,		atol=1e-4    )    )


