


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     __UpperCAmelCase							:


     """simple docstring"""


     def __init__(	self  ,       __A  ,       __A=13  ,       __A=7  ,       __A=True  ,       __A=True  ,       __A=True  ,       __A=True  ,       __A=99  ,       __A=32  ,       __A=5  ,       __A=4  ,       __A=4  ,       __A="gelu"  ,       __A=0.0  ,       __A=0.1  ,       __A=True  ,       __A=512  ,       __A=16  ,       __A=2  ,       __A=0.02  ,       __A=3  ,       __A=4  ,       __A=None  ,       ):
        __a					=  parent
        __a					=  batch_size
        __a					=  seq_length
        __a					=  is_training
        __a					=  use_input_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_multiple_size
        __a					=  hidden_act
        __a					=  hidden_dropout
        __a					=  attention_dropout
        __a					=  weight_tying
        __a					=  max_position_embeddings
        __a					=  type_vocab_size
        __a					=  type_sequence_label_size
        __a					=  initializer_range
        __a					=  num_labels
        __a					=  num_choices
        __a					=  scope


     def 	snake_case_  (	self    ):
        __a					=  ids_tensor([self.batch_size, self.seq_length]  ,       self.vocab_size    )

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

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

        __a					=  self.get_config()

        return config, input_ids, input_mask, token_labels


     def 	snake_case_  (	self    ):
        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=__a  ,       initializer_range=self.initializer_range  ,       )


     def 	snake_case_  (	self    ):
        __a					=  self.prepare_config_and_inputs()

        __a					=  True

        return config, input_ids, input_mask, token_labels


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A    ):
        __a					=  GPTNeoXJapaneseModel(config=__a    )
        model.to(__a    )
        model.eval()
        __a					=  model(__a  ,       attention_mask=__a    )
        __a					=  model(__a    )
        self.parent.assertEqual(result.last_hidden_state.shape  ,       (self.batch_size, self.seq_length, self.hidden_size)    )


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A    ):
        __a					=  True
        __a					=  GPTNeoXJapaneseModel(__a    )
        model.to(__a    )
        model.eval()
        __a					=  model(__a  ,       attention_mask=__a    )
        self.parent.assertEqual(result.last_hidden_state.shape  ,       (self.batch_size, self.seq_length, self.hidden_size)    )


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A  ,       __A    ):
        __a					=  GPTNeoXJapaneseForCausalLM(config=__a    )
        model.to(__a    )
        model.eval()
        __a					=  model(__a  ,       attention_mask=__a  ,       labels=__a    )
        self.parent.assertEqual(result.logits.shape  ,       (self.batch_size, self.seq_length, self.vocab_size)    )


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A    ):
        __a					=  True
        __a					=  GPTNeoXJapaneseForCausalLM(config=__a    )
        model.to(__a    )
        model.eval()

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

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

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

        __a					=  model(__a  ,       attention_mask=__a  ,       output_hidden_states=__a    )
        __a					=  output_from_no_past["hidden_states"][0]
        __a					=  model(
            __a  ,       attention_mask=__a  ,       past_key_values=__a  ,       output_hidden_states=__a  ,       )["hidden_states"][0]

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


     def 	snake_case_  (	self    ):
        __a					=  self.prepare_config_and_inputs()
        __a					=  config_and_inputs
        __a					=  {"input_ids": input_ids, "attention_mask": input_mask}
        return config, inputs_dict







@require_torch
class     __UpperCAmelCase							(       _UpperCamelCase ,					_UpperCamelCase ,					unittest.TestCase							):


     """simple docstring"""
     _lowerCamelCase   =      (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
     _lowerCamelCase   =      (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
     _lowerCamelCase   =      (
         {"feature-extraction": GPTNeoXJapaneseModel, "text-generation": GPTNeoXJapaneseForCausalLM}
         if is_torch_available()
         else {}
     )
     _lowerCamelCase   =      False
     _lowerCamelCase   =      False
     _lowerCamelCase   =      False
     _lowerCamelCase   =      False


     def 	snake_case_  (	self    ):
        __a					=  GPTNeoXJapaneseModelTester(self    )
        __a					=  ConfigTester(self  ,       config_class=__a  ,       hidden_size=37    )


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


     def 	snake_case_  (	self    ):
        __a					=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(__a  ,       __a  ,       __a    )


     def 	snake_case_  (	self    ):
        __a					=  self.model_tester.prepare_config_and_inputs_for_decoder()
        self.model_tester.create_and_check_model_as_decoder(__a  ,       __a  ,       __a    )


     def 	snake_case_  (	self    ):
        # This regression test was failing with PyTorch < 1.3
        __a					=  self.model_tester.prepare_config_and_inputs_for_decoder()

        __a					=  None

        self.model_tester.create_and_check_model_as_decoder(__a  ,       __a  ,       __a    )


     def 	snake_case_  (	self    ):
        __a					=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_decoder_model_past_large_inputs(__a  ,       __a  ,       __a    )


     def 	snake_case_  (	self    ):
        __a					=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_causal_lm(*__a    )


     @slow
     def 	snake_case_  (	self    ):
        __a					=  "abeja/gpt-neox-japanese-2.7b"

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

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

        __a					=  GPTNeoXJapaneseTokenizer.from_pretrained(__a    )
        __a					=  GPTNeoXJapaneseForCausalLM.from_pretrained(__a    )

        __a					=  []
        for prompt in prompts:
           __a					=  tokenizer(__a  ,       return_tensors="""pt"""    ).input_ids
           __a					=  model.generate(__a  ,       max_length=50    )
           __a					=  tokenizer.batch_decode(__a  ,       skip_special_tokens=__a    )
           predicted_outputs += generated_string
        self.assertListEqual(__a  ,       __a    )










"""simple docstring"""


import warnings


warnings.warn(
    "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: "
    "`from accelerate import find_executable_batch_size` to avoid this warning.",
    FutureWarning,
)
