




'''simple docstring'''


import unittest

from transformers import GPTNeoXJapaneseConfig, is_torch_available
from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
from transformers.testing_utils import require_torch, slow, torch_device

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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel
class 						a_				:




	def __init__(       self     :  List[Any]       ,		__lowerCAmelCase     :  Optional[int]       ,		__lowerCAmelCase     :  str=1_3       ,		__lowerCAmelCase     :  Optional[int]=7       ,		__lowerCAmelCase     :  Optional[int]=True       ,		__lowerCAmelCase     :  Union[str, Any]=True       ,		__lowerCAmelCase     :  Any=True       ,		__lowerCAmelCase     :  Optional[Any]=True       ,		__lowerCAmelCase     :  str=9_9       ,		__lowerCAmelCase     :  Tuple=3_2       ,		__lowerCAmelCase     :  int=5       ,		__lowerCAmelCase     :  Optional[Any]=4       ,		__lowerCAmelCase     :  Tuple=4       ,		__lowerCAmelCase     :  Union[str, Any]="gelu"       ,		__lowerCAmelCase     :  Optional[Any]=0.0       ,		__lowerCAmelCase     :  Tuple=0.1       ,		__lowerCAmelCase     :  Optional[int]=True       ,		__lowerCAmelCase     :  str=5_1_2       ,		__lowerCAmelCase     :  Dict=1_6       ,		__lowerCAmelCase     :  Optional[Any]=2       ,		__lowerCAmelCase     :  Dict=0.02       ,		__lowerCAmelCase     :  Optional[Any]=3       ,		__lowerCAmelCase     :  List[Any]=4       ,		__lowerCAmelCase     :  Union[str, Any]=None       ,		):
							__snake_case						 =   parent
							__snake_case						 =   batch_size
							__snake_case						 =   seq_length
							__snake_case						 =   is_training
							__snake_case						 =   use_input_mask
							__snake_case						 =   use_token_type_ids
							__snake_case						 =   use_labels
							__snake_case						 =   vocab_size
							__snake_case						 =   hidden_size
							__snake_case						 =   num_hidden_layers
							__snake_case						 =   num_attention_heads
							__snake_case						 =   intermediate_multiple_size
							__snake_case						 =   hidden_act
							__snake_case						 =   hidden_dropout
							__snake_case						 =   attention_dropout
							__snake_case						 =   weight_tying
							__snake_case						 =   max_position_embeddings
							__snake_case						 =   type_vocab_size
							__snake_case						 =   type_sequence_label_size
							__snake_case						 =   initializer_range
							__snake_case						 =   num_labels
							__snake_case						 =   num_choices
							__snake_case						 =   scope




	def   lowercase__   (       self     :  Dict      ):
							__snake_case						 =   ids_tensor([self.batch_size, self.seq_length]       ,		self.vocab_size      )

							__snake_case						 =   None
							if self.use_input_mask:
													__snake_case						 =   random_attention_mask([self.batch_size, self.seq_length]      )

							__snake_case						 =   None
							if self.use_labels:
													__snake_case						 =   ids_tensor([self.batch_size, self.seq_length]       ,		self.num_labels      )

							__snake_case						 =   self.get_config()

							return config, input_ids, input_mask, token_labels




	def   lowercase__   (       self     :  Union[str, Any]      ):
							return GPTNeoXJapaneseConfig(
							    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_multiple_size=self.intermediate_multiple_size       ,		hidden_act=self.hidden_act       ,		hidden_dropout=self.hidden_dropout       ,		attention_dropout=self.attention_dropout       ,		weight_tying=self.weight_tying       ,		max_position_embeddings=self.max_position_embeddings       ,		type_vocab_size=self.type_vocab_size       ,		is_decoder=__lowerCAmelCase       ,		initializer_range=self.initializer_range       ,		)




	def   lowercase__   (       self     :  Dict      ):
							__snake_case ,       __snake_case ,       __snake_case ,       __snake_case						 =   self.prepare_config_and_inputs()

							__snake_case						 =   True

							return config, input_ids, input_mask, token_labels




	def   lowercase__   (       self     :  List[Any]       ,		__lowerCAmelCase     :  Dict       ,		__lowerCAmelCase     :  Tuple       ,		__lowerCAmelCase     :  Dict      ):
							__snake_case						 =   GPTNeoXJapaneseModel(config=__lowerCAmelCase      )
							model.to(__lowerCAmelCase      )
							model.eval()
							__snake_case						 =   model(__lowerCAmelCase       ,		attention_mask=__lowerCAmelCase      )
							__snake_case						 =   model(__lowerCAmelCase      )
							self.parent.assertEqual(result.last_hidden_state.shape       ,		(self.batch_size, self.seq_length, self.hidden_size)      )




	def   lowercase__   (       self     :  int       ,		__lowerCAmelCase     :  Optional[int]       ,		__lowerCAmelCase     :  Any       ,		__lowerCAmelCase     :  str      ):
							__snake_case						 =   True
							__snake_case						 =   GPTNeoXJapaneseModel(__lowerCAmelCase      )
							model.to(__lowerCAmelCase      )
							model.eval()
							__snake_case						 =   model(__lowerCAmelCase       ,		attention_mask=__lowerCAmelCase      )
							self.parent.assertEqual(result.last_hidden_state.shape       ,		(self.batch_size, self.seq_length, self.hidden_size)      )




	def   lowercase__   (       self     :  Tuple       ,		__lowerCAmelCase     :  Dict       ,		__lowerCAmelCase     :  List[Any]       ,		__lowerCAmelCase     :  Optional[int]       ,		__lowerCAmelCase     :  int      ):
							__snake_case						 =   GPTNeoXJapaneseForCausalLM(config=__lowerCAmelCase      )
							model.to(__lowerCAmelCase      )
							model.eval()
							__snake_case						 =   model(__lowerCAmelCase       ,		attention_mask=__lowerCAmelCase       ,		labels=__lowerCAmelCase      )
							self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.seq_length, self.vocab_size)      )




	def   lowercase__   (       self     :  Any       ,		__lowerCAmelCase     :  Union[str, Any]       ,		__lowerCAmelCase     :  Optional[int]       ,		__lowerCAmelCase     :  Any      ):
							__snake_case						 =   True
							__snake_case						 =   GPTNeoXJapaneseForCausalLM(config=__lowerCAmelCase      )
							model.to(__lowerCAmelCase      )
							model.eval()

							# first forward pass
							__snake_case						 =   model(__lowerCAmelCase       ,		attention_mask=__lowerCAmelCase       ,		use_cache=__lowerCAmelCase      )
							__snake_case						 =   outputs.past_key_values

							# create hypothetical multiple next token and extent to next_input_ids
							__snake_case						 =   ids_tensor((self.batch_size, 3)       ,		config.vocab_size      )
							__snake_case						 =   ids_tensor((self.batch_size, 3)       ,		vocab_size=2      )

							# append to next input_ids and
							__snake_case						 =   torch.cat([input_ids, next_tokens]       ,		dim=-1      )
							__snake_case						 =   torch.cat([input_mask, next_mask]       ,		dim=-1      )

							__snake_case						 =   model(__lowerCAmelCase       ,		attention_mask=__lowerCAmelCase       ,		output_hidden_states=__lowerCAmelCase      )
							__snake_case						 =   output_from_no_past['hidden_states'][0]
							__snake_case						 =   model(
							    __lowerCAmelCase       ,		attention_mask=__lowerCAmelCase       ,		past_key_values=__lowerCAmelCase       ,		output_hidden_states=__lowerCAmelCase       ,		)['hidden_states'][0]

							# select random slice
							__snake_case						 =   ids_tensor((1,)       ,		output_from_past.shape[-1]      ).item()
							__snake_case						 =   output_from_no_past[:, -3:, random_slice_idx].detach()
							__snake_case						 =   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(__lowerCAmelCase       ,		__lowerCAmelCase       ,		atol=1E-3      )      )




	def   lowercase__   (       self     :  int      ):
							__snake_case						 =   self.prepare_config_and_inputs()
							__snake_case ,       __snake_case ,       __snake_case ,       __snake_case						 =   config_and_inputs
							__snake_case						 =   {'input_ids': input_ids, 'attention_mask': input_mask}
							return config, inputs_dict





@require_torch
class 						a_				(			UpperCAmelCase__     ,						UpperCAmelCase__     ,						unittest.TestCase						):
	lowercase_       :     Any			  =      (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
	lowercase_       :     Dict			  =      (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
	lowercase_       :     List[Any]			  =      (
	    {'''feature-extraction''': GPTNeoXJapaneseModel, '''text-generation''': GPTNeoXJapaneseForCausalLM}
	    if is_torch_available()
	    else {}
	)
	lowercase_       :     Optional[int]			  =      False
	lowercase_       :     Optional[Any]			  =      False
	lowercase_       :     str			  =      False
	lowercase_       :     Union[str, Any]			  =      False




	def   lowercase__   (       self     :  List[str]      ):
							__snake_case						 =   GPTNeoXJapaneseModelTester(self      )
							__snake_case						 =   ConfigTester(self       ,		config_class=__lowerCAmelCase       ,		hidden_size=3_7      )




	def   lowercase__   (       self     :  int      ):
							self.config_tester.run_common_tests()




	def   lowercase__   (       self     :  Any      ):
							__snake_case ,       __snake_case ,       __snake_case ,       __snake_case						 =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(__lowerCAmelCase       ,		__lowerCAmelCase       ,		__lowerCAmelCase      )




	def   lowercase__   (       self     :  int      ):
							__snake_case ,       __snake_case ,       __snake_case ,       __snake_case						 =   self.model_tester.prepare_config_and_inputs_for_decoder()
							self.model_tester.create_and_check_model_as_decoder(__lowerCAmelCase       ,		__lowerCAmelCase       ,		__lowerCAmelCase      )




	def   lowercase__   (       self     :  Dict      ):
							# This regression test was failing with PyTorch < 1.3
							__snake_case ,       __snake_case ,       __snake_case ,       __snake_case						 =   self.model_tester.prepare_config_and_inputs_for_decoder()

							__snake_case						 =   None

							self.model_tester.create_and_check_model_as_decoder(__lowerCAmelCase       ,		__lowerCAmelCase       ,		__lowerCAmelCase      )




	def   lowercase__   (       self     :  Any      ):
							__snake_case ,       __snake_case ,       __snake_case ,       __snake_case						 =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_decoder_model_past_large_inputs(__lowerCAmelCase       ,		__lowerCAmelCase       ,		__lowerCAmelCase      )




	def   lowercase__   (       self     :  Optional[int]      ):
							__snake_case						 =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_causal_lm(*__lowerCAmelCase      )




	@slow
	def   lowercase__   (       self     :  Any      ):
							__snake_case						 =   'abeja/gpt-neox-japanese-2.7b'

							__snake_case						 =   ['データサイエンティストとは、', '100年後に必要とされる会社は、', 'フルリモートの環境で働くために必要なことは、', '国境の長いトンネルを抜けると', '美味しい日本食といえば、']

							__snake_case						 =   [
							    'データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。',
							    '100年後に必要とされる会社は、「人」が中心の会社です。',
							    'フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。',
							    '国境の長いトンネルを抜けると、そこは雪国だった。',
							    '美味しい日本食といえば、やっぱりお寿司ですよね。',
							]

							__snake_case						 =   GPTNeoXJapaneseTokenizer.from_pretrained(__lowerCAmelCase      )
							__snake_case						 =   GPTNeoXJapaneseForCausalLM.from_pretrained(__lowerCAmelCase      )

							__snake_case						 =   []
							for prompt in prompts:
													__snake_case						 =   tokenizer(__lowerCAmelCase       ,		return_tensors='pt'      ).input_ids
													__snake_case						 =   model.generate(__lowerCAmelCase       ,		max_length=5_0      )
													__snake_case						 =   tokenizer.batch_decode(__lowerCAmelCase       ,		skip_special_tokens=__lowerCAmelCase      )
													predicted_outputs += generated_string
							self.assertListEqual(__lowerCAmelCase       ,		__lowerCAmelCase      )







'''simple docstring'''


import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_electra import ElectraTokenizer


_lowercase  =			{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

_lowercase  =			{
    """vocab_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""",
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-generator""": (
            """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json"""
        ),
    },
}

_lowercase  =			{
    """google/electra-small-generator""": 5_12,
    """google/electra-base-generator""": 5_12,
    """google/electra-large-generator""": 5_12,
    """google/electra-small-discriminator""": 5_12,
    """google/electra-base-discriminator""": 5_12,
    """google/electra-large-discriminator""": 5_12,
}

_lowercase  =			{
    """google/electra-small-generator""": {"""do_lower_case""": True},
    """google/electra-base-generator""": {"""do_lower_case""": True},
    """google/electra-large-generator""": {"""do_lower_case""": True},
    """google/electra-small-discriminator""": {"""do_lower_case""": True},
    """google/electra-base-discriminator""": {"""do_lower_case""": True},
    """google/electra-large-discriminator""": {"""do_lower_case""": True},
}
class 						a_				(			UpperCAmelCase__						):
	lowercase_       :     Tuple			  =      VOCAB_FILES_NAMES
	lowercase_       :     Optional[int]			  =      PRETRAINED_VOCAB_FILES_MAP
	lowercase_       :     int			  =      PRETRAINED_INIT_CONFIGURATION
	lowercase_       :     str			  =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowercase_       :     List[Any]			  =      ElectraTokenizer




	def __init__(       self     :  Optional[Any]       ,		__lowerCAmelCase     :  Optional[Any]=None       ,		__lowerCAmelCase     :  str=None       ,		__lowerCAmelCase     :  Union[str, Any]=True       ,		__lowerCAmelCase     :  int="[UNK]"       ,		__lowerCAmelCase     :  str="[SEP]"       ,		__lowerCAmelCase     :  Optional[Any]="[PAD]"       ,		__lowerCAmelCase     :  Optional[Any]="[CLS]"       ,		__lowerCAmelCase     :  str="[MASK]"       ,		__lowerCAmelCase     :  List[Any]=True       ,		__lowerCAmelCase     :  Optional[int]=None       ,		**__lowerCAmelCase     :  List[Any]       ,		):
							super().__init__(
							    __lowerCAmelCase       ,		tokenizer_file=__lowerCAmelCase       ,		do_lower_case=__lowerCAmelCase       ,		unk_token=__lowerCAmelCase       ,		sep_token=__lowerCAmelCase       ,		pad_token=__lowerCAmelCase       ,		cls_token=__lowerCAmelCase       ,		mask_token=__lowerCAmelCase       ,		tokenize_chinese_chars=__lowerCAmelCase       ,		strip_accents=__lowerCAmelCase       ,		**__lowerCAmelCase       ,		)

							__snake_case						 =   json.loads(self.backend_tokenizer.normalizer.__getstate__()      )
							if (
							    normalizer_state.get('lowercase'       ,		__lowerCAmelCase      ) != do_lower_case
							    or normalizer_state.get('strip_accents'       ,		__lowerCAmelCase      ) != strip_accents
							    or normalizer_state.get('handle_chinese_chars'       ,		__lowerCAmelCase      ) != tokenize_chinese_chars
							):
													__snake_case						 =   getattr(__lowerCAmelCase       ,		normalizer_state.pop('type'      )      )
													__snake_case						 =   do_lower_case
													__snake_case						 =   strip_accents
													__snake_case						 =   tokenize_chinese_chars
													__snake_case						 =   normalizer_class(**__lowerCAmelCase      )

							__snake_case						 =   do_lower_case




	def   lowercase__   (       self     :  Union[str, Any]       ,		__lowerCAmelCase     :  str       ,		__lowerCAmelCase     :  Tuple=None      ):
							__snake_case						 =   [self.cls_token_id] + token_ids_a + [self.sep_token_id]

							if token_ids_a:
													output += token_ids_a + [self.sep_token_id]

							return output




	def   lowercase__   (       self     :  Any       ,		__lowerCAmelCase     :  List[int]       ,		__lowerCAmelCase     :  Optional[List[int]] = None      ):
							__snake_case						 =   [self.sep_token_id]
							__snake_case						 =   [self.cls_token_id]
							if token_ids_a is None:
													return len(cls + token_ids_a + sep      ) * [0]
							return len(cls + token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1]




	def   lowercase__   (       self     :  List[Any]       ,		__lowerCAmelCase     :  str       ,		__lowerCAmelCase     :  Optional[str] = None      ):
							__snake_case						 =   self._tokenizer.model.save(__lowerCAmelCase       ,		name=__lowerCAmelCase      )
							return tuple(__lowerCAmelCase      )

