


import unittest

import numpy as np

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

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
				import jax.numpy as jnp

				from transformers.models.albert.modeling_flax_albert import (
				    FlaxAlbertForMaskedLM,
				    FlaxAlbertForMultipleChoice,
				    FlaxAlbertForPreTraining,
				    FlaxAlbertForQuestionAnswering,
				    FlaxAlbertForSequenceClassification,
				    FlaxAlbertForTokenClassification,
				    FlaxAlbertModel,
				)







class 	__lowercase    (unittest.TestCase  ):





							"""simple docstring"""







							def __init__(      self			,						lowerCAmelCase__			,						lowerCAmelCase__=1_3			,						lowerCAmelCase__=7			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=9_9			,						lowerCAmelCase__=3_2			,						lowerCAmelCase__=5			,						lowerCAmelCase__=4			,						lowerCAmelCase__=3_7			,						lowerCAmelCase__="gelu"			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=5_1_2			,						lowerCAmelCase__=1_6			,						lowerCAmelCase__=2			,						lowerCAmelCase__=0.02			,						lowerCAmelCase__=4			,						):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					parent
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					batch_size
										SCREAMING_SNAKE_CASE_		:     Dict					=					seq_length
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					is_training
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					use_attention_mask
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					use_token_type_ids
										SCREAMING_SNAKE_CASE_		:     str					=					use_labels
										SCREAMING_SNAKE_CASE_		:     str					=					vocab_size
										SCREAMING_SNAKE_CASE_		:     List[str]					=					hidden_size
										SCREAMING_SNAKE_CASE_		:     str					=					num_hidden_layers
										SCREAMING_SNAKE_CASE_		:     List[str]					=					num_attention_heads
										SCREAMING_SNAKE_CASE_		:     Dict					=					intermediate_size
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					hidden_act
										SCREAMING_SNAKE_CASE_		:     int					=					hidden_dropout_prob
										SCREAMING_SNAKE_CASE_		:     List[str]					=					attention_probs_dropout_prob
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					max_position_embeddings
										SCREAMING_SNAKE_CASE_		:     int					=					type_vocab_size
										SCREAMING_SNAKE_CASE_		:     Dict					=					type_sequence_label_size
										SCREAMING_SNAKE_CASE_		:     Dict					=					initializer_range
										SCREAMING_SNAKE_CASE_		:     Tuple					=					num_choices






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     str					=					ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size       )

										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					None
										if self.use_attention_mask:
													SCREAMING_SNAKE_CASE_		:     Dict					=					random_attention_mask([self.batch_size, self.seq_length]       )

										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					None
										if self.use_token_type_ids:
													SCREAMING_SNAKE_CASE_		:     List[str]					=					ids_tensor([self.batch_size, self.seq_length]			,						self.type_vocab_size       )

										SCREAMING_SNAKE_CASE_		:     str					=					AlbertConfig(
										    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 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




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







@require_flax
class 	__lowercase    (__SCREAMING_SNAKE_CASE	,       unittest.TestCase  ):





							"""simple docstring"""







							_UpperCAmelCase      =						(
							    (
							        FlaxAlbertModel,
							        FlaxAlbertForPreTraining,
							        FlaxAlbertForMaskedLM,
							        FlaxAlbertForMultipleChoice,
							        FlaxAlbertForQuestionAnswering,
							        FlaxAlbertForSequenceClassification,
							        FlaxAlbertForTokenClassification,
							        FlaxAlbertForQuestionAnswering,
							    )
							    if is_flax_available()
							    else ()
							)






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[str]					=					FlaxAlbertModelTester(self       )






							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										for model_class_name in self.all_model_classes:
													SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					model_class_name.from_pretrained('albert-base-v2'       )
													SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					model(np.ones((1, 1)       )       )
													self.assertIsNotNone(lowerCAmelCase__       )







@require_flax
class 	__lowercase    (unittest.TestCase  ):





							"""simple docstring"""







							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Tuple					=					FlaxAlbertModel.from_pretrained('albert-base-v2'       )
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]       )
										SCREAMING_SNAKE_CASE_		:     Any					=					np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]       )
										SCREAMING_SNAKE_CASE_		:     Any					=					model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__       )[0]
										SCREAMING_SNAKE_CASE_		:     str					=					(1, 1_1, 7_6_8)
										self.assertEqual(output.shape			,						lowerCAmelCase__       )
										SCREAMING_SNAKE_CASE_		:     Tuple					=					np.array(
										    [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]]       )

										self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]			,						lowerCAmelCase__			,						atol=1E-4       )       )










'''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 				a__(   lowerCamelCase__						,					unittest.TestCase      ):
    lowercase__					=       CodeGenTokenizer
    lowercase__					=       CodeGenTokenizerFast
    lowercase__					=       True
    lowercase__					=       {"""add_prefix_space""": True}
    lowercase__					=       False







    def      lowercase_			( self					:    List[str]      ):
      super().setUp()

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

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







    def      lowercase_			( self					:    Tuple		,     **__snake_case					:    Dict      ):
      kwargs.update(self.special_tokens_map      )
      return CodeGenTokenizer.from_pretrained(self.tmpdirname		,     **__snake_case      )







    def      lowercase_			( self					:    List[Any]		,     **__snake_case					:    List[str]      ):
      kwargs.update(self.special_tokens_map      )
      return CodeGenTokenizerFast.from_pretrained(self.tmpdirname		,     **__snake_case      )







    def      lowercase_			( self					:    Optional[int]		,     __snake_case					:    List[Any]      ):
      a		:   Tuple	  =	'lower newer'
      a		:   str	  =	'lower newer'
      return input_text, output_text







    def      lowercase_			( self					:    str      ):
      a		:   List[Any]	  =	CodeGenTokenizer(self.vocab_file		,     self.merges_file		,     **self.special_tokens_map      )
      a		:   Dict	  =	'lower newer'
      a		:   int	  =	['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er']
      a		:   List[str]	  =	tokenizer.tokenize(__snake_case		,     add_prefix_space=__snake_case      )
      self.assertListEqual(__snake_case		,     __snake_case      )

      a		:   Dict	  =	tokens + [tokenizer.unk_token]
      a		:   int	  =	[14, 15, 10, 9, 3, 2, 15, 19]
      self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case      )		,     __snake_case      )







    def      lowercase_			( self					:    List[Any]      ):
      if not self.test_rust_tokenizer:
        return

      a		:   Optional[int]	  =	self.get_tokenizer()
      a		:   Tuple	  =	self.get_rust_tokenizer(add_prefix_space=__snake_case      )

      a		:   List[str]	  =	'lower newer'

      # Testing tokenization
      a		:   Optional[int]	  =	tokenizer.tokenize(__snake_case		,     add_prefix_space=__snake_case      )
      a		:   Optional[Any]	  =	rust_tokenizer.tokenize(__snake_case      )
      self.assertListEqual(__snake_case		,     __snake_case      )

      # Testing conversion to ids without special tokens
      a		:   Tuple	  =	tokenizer.encode(__snake_case		,     add_special_tokens=__snake_case		,     add_prefix_space=__snake_case      )
      a		:   str	  =	rust_tokenizer.encode(__snake_case		,     add_special_tokens=__snake_case      )
      self.assertListEqual(__snake_case		,     __snake_case      )

      # Testing conversion to ids with special tokens
      a		:   Optional[int]	  =	self.get_rust_tokenizer(add_prefix_space=__snake_case      )
      a		:   Optional[int]	  =	tokenizer.encode(__snake_case		,     add_prefix_space=__snake_case      )
      a		:   Dict	  =	rust_tokenizer.encode(__snake_case      )
      self.assertListEqual(__snake_case		,     __snake_case      )

      # Testing the unknown token
      a		:   Any	  =	tokens + [rust_tokenizer.unk_token]
      a		:   List[Any]	  =	[14, 15, 10, 9, 3, 2, 15, 19]
      self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__snake_case      )		,     __snake_case      )







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







    def      lowercase_			( self					:    List[str]		,     __snake_case					:    str=15      ):
      for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
        with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""      ):
          a		:   List[Any]	  =	self.rust_tokenizer_class.from_pretrained(__snake_case		,     **__snake_case      )

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

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

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

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

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

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







    def      lowercase_			( self					:    Optional[Any]      ):
      a		:   Any	  =	CodeGenTokenizer.from_pretrained(self.tmpdirname		,     pad_token='<pad>'      )

      # Simple input
      a		:   Union[str, Any]	  =	'This is a simple input'
      a		:   Dict	  =	['This is a simple input looooooooong', 'This is a simple input']
      a		:   int	  =	('This is a simple input', 'This is a pair')
      a		:   List[Any]	  =	[
          ('This is a simple input loooooong', 'This is a simple input'),
          ('This is a simple pair loooooong', 'This is a simple pair'),
      ]

      a		:   Optional[int]	  =	tokenizer.pad_token_id

      a		:   List[Any]	  =	tokenizer(__snake_case		,     padding='max_length'		,     max_length=30		,     return_tensors='np'      )
      a		:   Union[str, Any]	  =	tokenizer(__snake_case		,     padding=__snake_case		,     truncate=__snake_case		,     return_tensors='np'      )
      a		:   Optional[Any]	  =	tokenizer(*__snake_case		,     padding='max_length'		,     max_length=60		,     return_tensors='np'      )
      a		:   List[Any]	  =	tokenizer(__snake_case		,     padding=__snake_case		,     truncate=__snake_case		,     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					:    Optional[int]      ):
      a		:   int	  =	'$$$'
      a		:   Dict	  =	CodeGenTokenizer.from_pretrained(self.tmpdirname		,     bos_token=__snake_case		,     add_bos_token=__snake_case      )

      a		:   int	  =	'This is a simple input'
      a		:   Tuple	  =	['This is a simple input 1', 'This is a simple input 2']

      a		:   Any	  =	tokenizer.bos_token_id

      a		:   Union[str, Any]	  =	tokenizer(__snake_case      )
      a		:   Dict	  =	tokenizer(__snake_case      )

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

      a		:   Optional[Any]	  =	tokenizer.decode(out_s.input_ids      )
      a		:   Optional[Any]	  =	tokenizer.batch_decode(out_sa.input_ids      )

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







    @slow
    def      lowercase_			( self					:    List[Any]      ):
      a		:   Tuple	  =	CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono'      )

      a		:   Union[str, Any]	  =	'\nif len_a > len_b:\n    result = a\nelse:\n    result = b\n\n\n\n#'
      a		:   Optional[Any]	  =	'\nif len_a > len_b:      result = a\nelse:      result = b'

      a		:   Any	  =	tokenizer.encode(__snake_case      )
      a		:   Union[str, Any]	  =	['^#', re.escape('<|endoftext|>'      ), '^\'\'\'', '^"""', '\n\n\n']
      a		:   List[str]	  =	tokenizer.decode(__snake_case		,     truncate_before_pattern=__snake_case      )
      self.assertEqual(__snake_case		,     __snake_case      )







    def      lowercase_			( self					:    Any      ):
      pass