






import json
import os
import unittest

from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import (
    VOCAB_FILES_NAMES,
    GPTNeoXJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin




@require_tokenizers
class        _lowerCAmelCase( UpperCAmelCase_							,			unittest.TestCase      ):





       """simple docstring"""







       a       :	Optional[int]								=GPTNeoXJapaneseTokenizer
       a       :	int								=False
       a       :	str								={'''do_clean_text''': False, '''add_prefix_space''': False}





       def     _a					(      self							):
         super().setUp()

         UpperCamelCase_:      Union[str, Any]					   =       [
             'こん',
             'こんに',
             'にちは',
             'ばんは',
             '世界,㔺界',
             '、',
             '。',
             '<BR>',
             '<SP>',
             '<TAB>',
             '<URL>',
             '<EMAIL>',
             '<TEL>',
             '<DATE>',
             '<PRICE>',
             '<BLOCK>',
             '<KIGOU>',
             '<U2000U2BFF>',
             '<|emoji1|>',
             '<unk>',
             '<|startoftext|>',
             '<|endoftext|>',
         ]
         UpperCamelCase_:      List[str]					   =       {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}}  # 😀
         UpperCamelCase_:      List[Any]					   =       {'unk_token': '<unk>'}

         UpperCamelCase_:      List[str]					   =       os.path.join(self.tmpdirname						,    VOCAB_FILES_NAMES['vocab_file']							)
         UpperCamelCase_:      int					   =       os.path.join(self.tmpdirname						,    VOCAB_FILES_NAMES['emoji_file']							)
         with open(self.vocab_file						,    'w'						,    encoding='utf-8'							) as vocab_writer:
           vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]							)							)
         with open(self.emoji_file						,    'w'							) as emoji_writer:
           emoji_writer.write(json.dumps(_lowerCamelCase							)							)





       def     _a					(      self						,    **_lowerCamelCase							):
         kwargs.update(self.special_tokens_map							)
         return GPTNeoXJapaneseTokenizer.from_pretrained(self.tmpdirname						,    **_lowerCamelCase							)





       def     _a					(      self						,    _lowerCamelCase							):
         UpperCamelCase_:      Optional[Any]					   =       'こんにちは、世界。 \nこんばんは、㔺界。😀'
         UpperCamelCase_:      int					   =       'こんにちは、世界。 \nこんばんは、世界。😀'
         return input_text, output_text





       def     _a					(      self						,    _lowerCamelCase							):
         UpperCamelCase_   ,UpperCamelCase_:      Union[str, Any]					   =       self.get_input_output_texts(_lowerCamelCase							)
         UpperCamelCase_:      Optional[int]					   =       tokenizer.encode(_lowerCamelCase						,    add_special_tokens=_lowerCamelCase							)
         UpperCamelCase_:      Dict					   =       tokenizer.decode(_lowerCamelCase						,    clean_up_tokenization_spaces=_lowerCamelCase							)
         return text, ids





       def     _a					(      self							):
         pass  # TODO add if relevant





       def     _a					(      self							):
         pass  # TODO add if relevant





       def     _a					(      self							):
         pass  # TODO add if relevant





       def     _a					(      self							):
         UpperCamelCase_:      Any					   =       self.get_tokenizer()

         # Testing tokenization
         UpperCamelCase_:      Dict					   =       'こんにちは、世界。　こんばんは、㔺界。'
         UpperCamelCase_:      Dict					   =       ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。']
         UpperCamelCase_:      Dict					   =       tokenizer.tokenize(_lowerCamelCase							)
         self.assertListEqual(_lowerCamelCase						,    _lowerCamelCase							)

         # Testing conversion to ids without special tokens
         UpperCamelCase_:      Optional[int]					   =       [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
         UpperCamelCase_:      Union[str, Any]					   =       tokenizer.convert_tokens_to_ids(_lowerCamelCase							)
         self.assertListEqual(_lowerCamelCase						,    _lowerCamelCase							)

         # Testing conversion to ids with special tokens
         UpperCamelCase_:      List[str]					   =       tokens + [tokenizer.unk_token]
         UpperCamelCase_:      Any					   =       [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9]
         UpperCamelCase_:      Union[str, Any]					   =       tokenizer.convert_tokens_to_ids(_lowerCamelCase							)
         self.assertListEqual(_lowerCamelCase						,    _lowerCamelCase							)





       @slow
       def     _a					(      self							):
         UpperCamelCase_:      Any					   =       self.tokenizer_class.from_pretrained('abeja/gpt-neox-japanese-2.7b'							)

         UpperCamelCase_:      List[Any]					   =       tokenizer.encode('ありがとう。'						,    add_special_tokens=_lowerCamelCase							)
         UpperCamelCase_:      str					   =       tokenizer.encode('どういたしまして。'						,    add_special_tokens=_lowerCamelCase							)

         UpperCamelCase_:      Tuple					   =       tokenizer.build_inputs_with_special_tokens(_lowerCamelCase							)
         UpperCamelCase_:      Dict					   =       tokenizer.build_inputs_with_special_tokens(_lowerCamelCase						,    _lowerCamelCase							)

         assert encoded_sentence == ids_a
         assert encoded_pair == ids_a + ids_a





       def     _a					(      self							):
         # Intentionally convert some words to accommodate character fluctuations unique to Japanese
         pass





       def     _a					(      self							):
         # tokenizer has no padding token
         pass







from __future__ import annotations

import unittest

from transformers import CTRLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers.models.ctrl.modeling_tf_ctrl import (
       TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFCTRLForSequenceClassification,
       TFCTRLLMHeadModel,
       TFCTRLModel,
   )




class        _lowerCAmelCase( UpperCAmelCase_      ):





       """simple docstring"""







       def __init__(      self						,    _lowerCamelCase						,    ):
         UpperCamelCase_:      Tuple					   =       parent
         UpperCamelCase_:      Optional[Any]					   =       1_3
         UpperCamelCase_:      Any					   =       7
         UpperCamelCase_:      Any					   =       True
         UpperCamelCase_:      List[Any]					   =       True
         UpperCamelCase_:      Dict					   =       True
         UpperCamelCase_:      Optional[Any]					   =       True
         UpperCamelCase_:      Tuple					   =       True
         UpperCamelCase_:      Any					   =       9_9
         UpperCamelCase_:      Dict					   =       3_2
         UpperCamelCase_:      Dict					   =       2
         UpperCamelCase_:      List[Any]					   =       4
         UpperCamelCase_:      int					   =       3_7
         UpperCamelCase_:      List[str]					   =       'gelu'
         UpperCamelCase_:      Union[str, Any]					   =       0.1
         UpperCamelCase_:      int					   =       0.1
         UpperCamelCase_:      int					   =       5_1_2
         UpperCamelCase_:      str					   =       1_6
         UpperCamelCase_:      List[str]					   =       2
         UpperCamelCase_:      Optional[int]					   =       0.0_2
         UpperCamelCase_:      int					   =       3
         UpperCamelCase_:      Tuple					   =       4
         UpperCamelCase_:      List[Any]					   =       None
         UpperCamelCase_:      Union[str, Any]					   =       self.vocab_size - 1





       def     _a					(      self							):
         UpperCamelCase_:      Optional[Any]					   =       ids_tensor([self.batch_size, self.seq_length]						,    self.vocab_size							)

         UpperCamelCase_:      List[str]					   =       None
         if self.use_input_mask:
           UpperCamelCase_:      str					   =       random_attention_mask([self.batch_size, self.seq_length]							)

         UpperCamelCase_:      Optional[Any]					   =       None
         if self.use_token_type_ids:
           UpperCamelCase_:      str					   =       ids_tensor([self.batch_size, self.seq_length]						,    self.type_vocab_size							)

         UpperCamelCase_:      Dict					   =       None
         if self.use_mc_token_ids:
           UpperCamelCase_:      str					   =       ids_tensor([self.batch_size, self.num_choices]						,    self.seq_length							)

         UpperCamelCase_:      Any					   =       None
         UpperCamelCase_:      Any					   =       None
         UpperCamelCase_:      Dict					   =       None
         if self.use_labels:
           UpperCamelCase_:      str					   =       ids_tensor([self.batch_size]						,    self.type_sequence_label_size							)
           UpperCamelCase_:      Dict					   =       ids_tensor([self.batch_size, self.seq_length]						,    self.num_labels							)
           UpperCamelCase_:      Union[str, Any]					   =       ids_tensor([self.batch_size]						,    self.num_choices							)

         UpperCamelCase_:      List[str]					   =       CTRLConfig(
             vocab_size=self.vocab_size						,    n_embd=self.hidden_size						,    n_layer=self.num_hidden_layers						,    n_head=self.num_attention_heads						,    n_positions=self.max_position_embeddings						,    pad_token_id=self.pad_token_id						,    )

         UpperCamelCase_:      Tuple					   =       ids_tensor([self.num_hidden_layers, self.num_attention_heads]						,    2							)

         return (
             config,
             input_ids,
             input_mask,
             head_mask,
             token_type_ids,
             mc_token_ids,
             sequence_labels,
             token_labels,
             choice_labels,
         )





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    *_lowerCamelCase							):
         UpperCamelCase_:      Dict					   =       TFCTRLModel(config=_lowerCamelCase							)
         UpperCamelCase_:      int					   =       {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         UpperCamelCase_:      Optional[int]					   =       model(_lowerCamelCase							)

         UpperCamelCase_:      Optional[int]					   =       [input_ids, None, input_mask]  # None is the input for 'past'
         UpperCamelCase_:      Dict					   =       model(_lowerCamelCase							)

         UpperCamelCase_:      List[str]					   =       model(_lowerCamelCase							)

         self.parent.assertEqual(result.last_hidden_state.shape						,    (self.batch_size, self.seq_length, self.hidden_size)							)





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    *_lowerCamelCase							):
         UpperCamelCase_:      int					   =       TFCTRLLMHeadModel(config=_lowerCamelCase							)
         UpperCamelCase_:      Optional[int]					   =       {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         UpperCamelCase_:      List[Any]					   =       model(_lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.seq_length, self.vocab_size)							)





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    *_lowerCamelCase							):
         UpperCamelCase_:      List[str]					   =       self.num_labels
         UpperCamelCase_:      Dict					   =       ids_tensor([self.batch_size]						,    self.type_sequence_label_size							)
         UpperCamelCase_:      List[Any]					   =       {
             'input_ids': input_ids,
             'token_type_ids': token_type_ids,
             'labels': sequence_labels,
         }
         UpperCamelCase_:      List[str]					   =       TFCTRLForSequenceClassification(_lowerCamelCase							)
         UpperCamelCase_:      Tuple					   =       model(_lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.num_labels)							)





       def     _a					(      self							):
         UpperCamelCase_:      int					   =       self.prepare_config_and_inputs()

         (
             (
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,(
             UpperCamelCase_
         )   ,
         ):      str					   =       config_and_inputs

         UpperCamelCase_:      List[str]					   =       {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
         return config, inputs_dict







@require_tf
class        _lowerCAmelCase( UpperCAmelCase_							,			UpperCAmelCase_							,			unittest.TestCase      ):





       """simple docstring"""







       a       :	Tuple								=(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
       a       :	str								=(TFCTRLLMHeadModel,) if is_tf_available() else ()
       a       :	int								=(
           {
               '''feature-extraction''': TFCTRLModel,
               '''text-classification''': TFCTRLForSequenceClassification,
               '''text-generation''': TFCTRLLMHeadModel,
               '''zero-shot''': TFCTRLForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       a       :	Tuple								=False
       a       :	str								=False





       def     _a					(      self						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase						,    _lowerCamelCase							):
         if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
           # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
           # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
           # config could not be created.
           return True

         return False





       def     _a					(      self							):
         UpperCamelCase_:      List[str]					   =       TFCTRLModelTester(self							)
         UpperCamelCase_:      List[Any]					   =       ConfigTester(self						,    config_class=_lowerCamelCase						,    n_embd=3_7							)





       def     _a					(      self							):
         self.config_tester.run_common_tests()





       def     _a					(      self							):
         UpperCamelCase_:      Dict					   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_model(*_lowerCamelCase							)





       def     _a					(      self							):
         UpperCamelCase_:      Optional[int]					   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_lm_head(*_lowerCamelCase							)





       def     _a					(      self							):
         UpperCamelCase_:      Union[str, Any]					   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_ctrl_for_sequence_classification(*_lowerCamelCase							)





       def     _a					(      self							):
         UpperCamelCase_   ,UpperCamelCase_:      Union[str, Any]					   =       self.model_tester.prepare_config_and_inputs_for_common()
         UpperCamelCase_:      Optional[Any]					   =       [TFCTRLLMHeadModel]
         UpperCamelCase_:      Optional[Any]					   =       [TFCTRLForSequenceClassification]

         for model_class in self.all_model_classes:
           UpperCamelCase_:      Union[str, Any]					   =       model_class(_lowerCamelCase							)
           model.build()  # may be needed for the get_bias() call below
           assert isinstance(model.get_input_embeddings()						,    tf.keras.layers.Layer							)

           if model_class in list_lm_models:
             UpperCamelCase_:      str					   =       model.get_output_embeddings()
             assert isinstance(_lowerCamelCase						,    tf.keras.layers.Layer							)
             UpperCamelCase_:      List[Any]					   =       model.get_bias()
             assert isinstance(_lowerCamelCase						,    _lowerCamelCase							)
             for k, v in name.items():
               assert isinstance(_lowerCamelCase						,    tf.Variable							)
           elif model_class in list_other_models_with_output_ebd:
             UpperCamelCase_:      Any					   =       model.get_output_embeddings()
             assert isinstance(_lowerCamelCase						,    tf.keras.layers.Layer							)
             UpperCamelCase_:      List[Any]					   =       model.get_bias()
             assert name is None
           else:
             UpperCamelCase_:      Dict					   =       model.get_output_embeddings()
             assert x is None
             UpperCamelCase_:      Optional[int]					   =       model.get_bias()
             assert name is None





       @slow
       def     _a					(      self							):
         for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase_:      Optional[Any]					   =       TFCTRLModel.from_pretrained(_lowerCamelCase							)
           self.assertIsNotNone(_lowerCamelCase							)







@require_tf
class        _lowerCAmelCase( unittest.TestCase      ):





       """simple docstring"""







       @slow
       def     _a					(      self							):
         UpperCamelCase_:      Optional[int]					   =       TFCTRLLMHeadModel.from_pretrained('ctrl'							)
         UpperCamelCase_:      Any					   =       tf.convert_to_tensor([[1_1_8_5_9, 0, 1_6_1_1, 8]]						,    dtype=tf.intaa							)  # Legal the president is
         UpperCamelCase_:      Dict					   =       [
             1_1_8_5_9,
             0,
             1_6_1_1,
             8,
             5,
             1_5_0,
             2_6_4_4_9,
             2,
             1_9,
             3_4_8,
             4_6_9,
             3,
             2_5_9_5,
             4_8,
             2_0_7_4_0,
             2_4_6_5_3_3,
             2_4_6_5_3_3,
             1_9,
             3_0,
             5,
         ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

         UpperCamelCase_:      List[str]					   =       model.generate(_lowerCamelCase						,    do_sample=_lowerCamelCase							)
         self.assertListEqual(output_ids[0].numpy().tolist()						,    _lowerCamelCase							)