
"""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			:				Optional[int]							,   UpperCAmelCase_			:				Any							,   UpperCAmelCase_			:				str=13							,   UpperCAmelCase_			:				Optional[int]=7							,   UpperCAmelCase_			:				Optional[int]=True							,   UpperCAmelCase_			:				Optional[Any]=True							,   UpperCAmelCase_			:				Optional[int]=True							,   UpperCAmelCase_			:				int=True							,   UpperCAmelCase_			:				Dict=99							,   UpperCAmelCase_			:				str=32							,   UpperCAmelCase_			:				List[Any]=5							,   UpperCAmelCase_			:				str=4							,   UpperCAmelCase_			:				Union[str, Any]=4							,   UpperCAmelCase_			:				Optional[int]="gelu"							,   UpperCAmelCase_			:				Tuple=0.0							,   UpperCAmelCase_			:				Any=0.1							,   UpperCAmelCase_			:				int=True							,   UpperCAmelCase_			:				Union[str, Any]=512							,   UpperCAmelCase_			:				int=16							,   UpperCAmelCase_			:				Optional[Any]=2							,   UpperCAmelCase_			:				str=0.02							,   UpperCAmelCase_			:				Any=3							,   UpperCAmelCase_			:				Any=4							,   UpperCAmelCase_			:				Optional[Any]=None							,   )->	Tuple:







              """simple docstring"""
              UpperCamelCase       			=		parent
              UpperCamelCase       			=		batch_size
              UpperCamelCase       			=		seq_length
              UpperCamelCase       			=		is_training
              UpperCamelCase       			=		use_input_mask
              UpperCamelCase       			=		use_token_type_ids
              UpperCamelCase       			=		use_labels
              UpperCamelCase       			=		vocab_size
              UpperCamelCase       			=		hidden_size
              UpperCamelCase       			=		num_hidden_layers
              UpperCamelCase       			=		num_attention_heads
              UpperCamelCase       			=		intermediate_multiple_size
              UpperCamelCase       			=		hidden_act
              UpperCamelCase       			=		hidden_dropout
              UpperCamelCase       			=		attention_dropout
              UpperCamelCase       			=		weight_tying
              UpperCamelCase       			=		max_position_embeddings
              UpperCamelCase       			=		type_vocab_size
              UpperCamelCase       			=		type_sequence_label_size
              UpperCamelCase       			=		initializer_range
              UpperCamelCase       			=		num_labels
              UpperCamelCase       			=		num_choices
              UpperCamelCase       			=		scope






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	Union[str, Any]:







              """simple docstring"""
              UpperCamelCase       			=		ids_tensor([self.batch_size, self.seq_length]							,   self.vocab_size      )

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

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

              UpperCamelCase       			=		self.get_config()

              return config, input_ids, input_mask, token_labels






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict      )->	Dict:







              """simple docstring"""
              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=UpperCAmelCase_							,   initializer_range=self.initializer_range							,   )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	List[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.prepare_config_and_inputs()

              UpperCamelCase       			=		True

              return config, input_ids, input_mask, token_labels






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Union[str, Any]							,   UpperCAmelCase_			:				List[Any]							,   UpperCAmelCase_			:				Union[str, Any]							,   UpperCAmelCase_			:				List[Any]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		GPTNeoXJapaneseModel(config=UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()
              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_      )
              UpperCamelCase       			=		model(UpperCAmelCase_      )
              self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, self.seq_length, self.hidden_size)      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any							,   UpperCAmelCase_			:				List[str]							,   UpperCAmelCase_			:				List[Any]							,   UpperCAmelCase_			:				List[str]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		True
              UpperCamelCase       			=		GPTNeoXJapaneseModel(UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()
              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_      )
              self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, self.seq_length, self.hidden_size)      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]							,   UpperCAmelCase_			:				Tuple							,   UpperCAmelCase_			:				Dict							,   UpperCAmelCase_			:				List[Any]							,   UpperCAmelCase_			:				Optional[Any]      )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()
              UpperCamelCase       			=		model(UpperCAmelCase_							,   attention_mask=UpperCAmelCase_							,   labels=UpperCAmelCase_      )
              self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.seq_length, self.vocab_size)      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict							,   UpperCAmelCase_			:				int							,   UpperCAmelCase_			:				Optional[int]							,   UpperCAmelCase_			:				Optional[Any]      )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		True
              UpperCamelCase       			=		GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()

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

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

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

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

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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[Any]      )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		self.prepare_config_and_inputs()
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		config_and_inputs
              UpperCamelCase       			=		{"input_ids": input_ids, "attention_mask": input_mask}
              return config, inputs_dict





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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		GPTNeoXJapaneseModelTester(self      )
              UpperCamelCase       			=		ConfigTester(self							,   config_class=UpperCAmelCase_							,   hidden_size=37      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				str      )->	Any:







              """simple docstring"""
              self.config_tester.run_common_tests()






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	Dict:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	Optional[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs_for_decoder()
              self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict      )->	List[Any]:







              """simple docstring"""
              # This regression test was failing with PyTorch < 1.3
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs_for_decoder()

              UpperCamelCase       			=		None

              self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	List[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_decoder_model_past_large_inputs(UpperCAmelCase_							,   UpperCAmelCase_							,   UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	Optional[int]:







              """simple docstring"""
              UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase_      )






       @slow
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict      )->	str:







              """simple docstring"""
              UpperCamelCase       			=		"abeja/gpt-neox-japanese-2.7b"

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

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

              UpperCamelCase       			=		GPTNeoXJapaneseTokenizer.from_pretrained(UpperCAmelCase_      )
              UpperCamelCase       			=		GPTNeoXJapaneseForCausalLM.from_pretrained(UpperCAmelCase_      )

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







"""simple docstring"""


from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer



@dataclass
class 	__a	(   _lowerCAmelCase						):
       UpperCamelCase_		:       torch.FloatTensor





class 	__a	(   _lowerCAmelCase     ,  _lowerCAmelCase						):






       @register_to_config
       def __init__(	self			:				int							,   UpperCAmelCase_			:				int = 3							,   UpperCAmelCase_			:				int = 3							,   UpperCAmelCase_			:				Tuple[str] = ("DownEncoderBlock2D",)							,   UpperCAmelCase_			:				Tuple[str] = ("UpDecoderBlock2D",)							,   UpperCAmelCase_			:				Tuple[int] = (64,)							,   UpperCAmelCase_			:				int = 1							,   UpperCAmelCase_			:				str = "silu"							,   UpperCAmelCase_			:				int = 3							,   UpperCAmelCase_			:				int = 32							,   UpperCAmelCase_			:				int = 256							,   UpperCAmelCase_			:				int = 32							,   UpperCAmelCase_			:				Optional[int] = None							,   UpperCAmelCase_			:				float = 0.18215							,   UpperCAmelCase_			:				str = "group"							,   )->	Optional[Any]:







              """simple docstring"""
              super().__init__()

              # pass init params to Encoder
              UpperCamelCase       			=		Encoder(
                  in_channels=UpperCAmelCase_							,   out_channels=UpperCAmelCase_							,   down_block_types=UpperCAmelCase_							,   block_out_channels=UpperCAmelCase_							,   layers_per_block=UpperCAmelCase_							,   act_fn=UpperCAmelCase_							,   norm_num_groups=UpperCAmelCase_							,   double_z=UpperCAmelCase_							,   )

              UpperCamelCase       			=		vq_embed_dim if vq_embed_dim is not None else latent_channels

              UpperCamelCase       			=		nn.Convad(UpperCAmelCase_							,   UpperCAmelCase_							,   1      )
              UpperCamelCase       			=		VectorQuantizer(UpperCAmelCase_							,   UpperCAmelCase_							,   beta=0.25							,   remap=UpperCAmelCase_							,   sane_index_shape=UpperCAmelCase_      )
              UpperCamelCase       			=		nn.Convad(UpperCAmelCase_							,   UpperCAmelCase_							,   1      )

              # pass init params to Decoder
              UpperCamelCase       			=		Decoder(
                  in_channels=UpperCAmelCase_							,   out_channels=UpperCAmelCase_							,   up_block_types=UpperCAmelCase_							,   block_out_channels=UpperCAmelCase_							,   layers_per_block=UpperCAmelCase_							,   act_fn=UpperCAmelCase_							,   norm_num_groups=UpperCAmelCase_							,   norm_type=UpperCAmelCase_							,   )






       @apply_forward_hook
       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]							,   UpperCAmelCase_			:				torch.FloatTensor							,   UpperCAmelCase_			:				bool = True      )->	VQEncoderOutput:







              """simple docstring"""
              UpperCamelCase       			=		self.encoder(UpperCAmelCase_      )
              UpperCamelCase       			=		self.quant_conv(UpperCAmelCase_      )

              if not return_dict:
                     return (h,)

              return VQEncoderOutput(latents=UpperCAmelCase_      )






       @apply_forward_hook
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[Any]							,   UpperCAmelCase_			:				torch.FloatTensor							,   UpperCAmelCase_			:				bool = False							,   UpperCAmelCase_			:				bool = True      )->	Union[DecoderOutput, torch.FloatTensor]:







              """simple docstring"""
              # also go through quantization layer
              if not force_not_quantize:
                     UpperCamelCase			,							UpperCamelCase			,							UpperCamelCase       			=		self.quantize(UpperCAmelCase_      )
              else:
                     UpperCamelCase       			=		h
              UpperCamelCase       			=		self.post_quant_conv(UpperCAmelCase_      )
              UpperCamelCase       			=		self.decoder(UpperCAmelCase_							,   quant if self.config.norm_type == "spatial" else None      )

              if not return_dict:
                     return (dec,)

              return DecoderOutput(sample=UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Union[str, Any]							,   UpperCAmelCase_			:				torch.FloatTensor							,   UpperCAmelCase_			:				bool = True      )->	Union[DecoderOutput, torch.FloatTensor]:







              """simple docstring"""
              UpperCamelCase       			=		sample
              UpperCamelCase       			=		self.encode(UpperCAmelCase_      ).latents
              UpperCamelCase       			=		self.decode(UpperCAmelCase_      ).sample

              if not return_dict:
                     return (dec,)

              return DecoderOutput(sample=UpperCAmelCase_      )





