


from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


_SCREAMING_SNAKE_CASE      :			Optional[int]      				=   logging.get_logger(__name__)

class   A__ (   snake_case__     ):







    """simple docstring"""

    __magic_name__        =		['pixel_values']
    def __init__(	self      , __snake_case = True      , __snake_case = None      , __snake_case = None      , __snake_case = PILImageResampling.BILINEAR      , __snake_case = True      , __snake_case = 1 / 2_5_5      , __snake_case = True      , __snake_case = None      , __snake_case = None      , **__snake_case      , ):
         super().__init__(**__snake_case   )
         snake_case					=    size if size is not None else {'''shortest_edge''': 3_8_4}
         snake_case					=    get_size_dict(__snake_case      , default_to_square=__snake_case   )

         snake_case					=    do_resize
         snake_case					=    size
         # Default value set here for backwards compatibility where the value in config is None
         snake_case					=    crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
         snake_case					=    resample
         snake_case					=    do_rescale
         snake_case					=    rescale_factor
         snake_case					=    do_normalize
         snake_case					=    image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         snake_case					=    image_std if image_std is not None else IMAGENET_STANDARD_STD
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case      , __snake_case = PILImageResampling.BICUBIC      , __snake_case = None      , **__snake_case      , ):
         snake_case					=    get_size_dict(__snake_case      , default_to_square=__snake_case   )
         if "shortest_edge" not in size:
              raise ValueError(F'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}'''   )
         snake_case					=    size['''shortest_edge''']

         if shortest_edge < 3_8_4:
              # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
              snake_case					=    int(shortest_edge / crop_pct   )
              snake_case					=    get_resize_output_image_size(__snake_case      , size=__snake_case      , default_to_square=__snake_case   )
              snake_case					=    resize(image=__snake_case      , size=__snake_case      , resample=__snake_case      , data_format=__snake_case      , **__snake_case   )
              # then crop to (shortest_edge, shortest_edge)
              return center_crop(image=__snake_case      , size=(shortest_edge, shortest_edge)      , data_format=__snake_case      , **__snake_case   )
         else:
              # warping (no cropping) when evaluated at 384 or larger
              return resize(
                  __snake_case      , size=(shortest_edge, shortest_edge)      , resample=__snake_case      , data_format=__snake_case      , **__snake_case   )
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case = None      , **__snake_case      , ):
         return rescale(__snake_case      , scale=__snake_case      , data_format=__snake_case      , **__snake_case   )
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case      , __snake_case = None      , **__snake_case      , ):
         return normalize(__snake_case      , mean=__snake_case      , std=__snake_case      , data_format=__snake_case      , **__snake_case   )




    def 		a_      (	self      , __snake_case      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = None      , __snake_case = ChannelDimension.FIRST      , **__snake_case      , ):
         snake_case					=    do_resize if do_resize is not None else self.do_resize
         snake_case					=    crop_pct if crop_pct is not None else self.crop_pct
         snake_case					=    resample if resample is not None else self.resample
         snake_case					=    do_rescale if do_rescale is not None else self.do_rescale
         snake_case					=    rescale_factor if rescale_factor is not None else self.rescale_factor
         snake_case					=    do_normalize if do_normalize is not None else self.do_normalize
         snake_case					=    image_mean if image_mean is not None else self.image_mean
         snake_case					=    image_std if image_std is not None else self.image_std

         snake_case					=    size if size is not None else self.size
         snake_case					=    get_size_dict(__snake_case      , default_to_square=__snake_case   )

         snake_case					=    make_list_of_images(__snake_case   )

         if not valid_images(__snake_case   ):
              raise ValueError(
                  '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                  '''torch.Tensor, tf.Tensor or jax.ndarray.'''   )

         if do_resize and size is None or resample is None:
              raise ValueError('''Size and resample must be specified if do_resize is True.'''   )

         if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
              raise ValueError('''crop_pct must be specified if size < 384.'''   )

         if do_rescale and rescale_factor is None:
              raise ValueError('''Rescale factor must be specified if do_rescale is True.'''   )

         if do_normalize and (image_mean is None or image_std is None):
              raise ValueError('''Image mean and std must be specified if do_normalize is True.'''   )

         # All transformations expect numpy arrays.
         snake_case					=    [to_numpy_array(__snake_case   ) for image in images]

         if do_resize:
              snake_case					=    [self.resize(image=__snake_case      , size=__snake_case      , crop_pct=__snake_case      , resample=__snake_case   ) for image in images]

         if do_rescale:
              snake_case					=    [self.rescale(image=__snake_case      , scale=__snake_case   ) for image in images]

         if do_normalize:
              snake_case					=    [self.normalize(image=__snake_case      , mean=__snake_case      , std=__snake_case   ) for image in images]

         snake_case					=    [to_channel_dimension_format(__snake_case      , __snake_case   ) for image in images]

         snake_case					=    {'''pixel_values''': images}
         return BatchFeature(data=__snake_case      , tensor_type=__snake_case   )








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







    """simple docstring"""

    def __init__(	self      , __snake_case      , __snake_case=1_3      , __snake_case=7      , __snake_case=True      , __snake_case=True      , __snake_case=True      , __snake_case=True      , __snake_case=9_9      , __snake_case=3_2      , __snake_case=5      , __snake_case=4      , __snake_case=4      , __snake_case="gelu"      , __snake_case=0.0      , __snake_case=0.1      , __snake_case=True      , __snake_case=5_1_2      , __snake_case=1_6      , __snake_case=2      , __snake_case=0.02      , __snake_case=3      , __snake_case=4      , __snake_case=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 		a_      (	self   ):
         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 		a_      (	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=__snake_case      , initializer_range=self.initializer_range      , )
    def 		a_      (	self   ):
         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 		a_      (	self      , __snake_case      , __snake_case      , __snake_case   ):
         snake_case					=    GPTNeoXJapaneseModel(config=__snake_case   )
         model.to(__snake_case   )
         model.eval()
         snake_case					=    model(__snake_case      , attention_mask=__snake_case   )
         snake_case					=    model(__snake_case   )
         self.parent.assertEqual(result.last_hidden_state.shape      , (self.batch_size, self.seq_length, self.hidden_size)   )
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case   ):
         snake_case					=    True
         snake_case					=    GPTNeoXJapaneseModel(__snake_case   )
         model.to(__snake_case   )
         model.eval()
         snake_case					=    model(__snake_case      , attention_mask=__snake_case   )
         self.parent.assertEqual(result.last_hidden_state.shape      , (self.batch_size, self.seq_length, self.hidden_size)   )
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case      , __snake_case   ):
         snake_case					=    GPTNeoXJapaneseForCausalLM(config=__snake_case   )
         model.to(__snake_case   )
         model.eval()
         snake_case					=    model(__snake_case      , attention_mask=__snake_case      , labels=__snake_case   )
         self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.seq_length, self.vocab_size)   )
    def 		a_      (	self      , __snake_case      , __snake_case      , __snake_case   ):
         snake_case					=    True
         snake_case					=    GPTNeoXJapaneseForCausalLM(config=__snake_case   )
         model.to(__snake_case   )
         model.eval()

         # first forward pass
         snake_case					=    model(__snake_case      , attention_mask=__snake_case      , use_cache=__snake_case   )
         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(__snake_case      , attention_mask=__snake_case      , output_hidden_states=__snake_case   )
         snake_case					=    output_from_no_past['''hidden_states'''][0]
         snake_case					=    model(
             __snake_case      , attention_mask=__snake_case      , past_key_values=__snake_case      , output_hidden_states=__snake_case      , )['''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(__snake_case      , __snake_case      , atol=1E-3   )   )




    def 		a_      (	self   ):
         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__ (   snake_case__	, snake_case__	, unittest.TestCase     ):







    """simple docstring"""

    __magic_name__        =		(GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
    __magic_name__        =		(GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
    __magic_name__        =		(
        {'feature-extraction': GPTNeoXJapaneseModel, 'text-generation': GPTNeoXJapaneseForCausalLM}
        if is_torch_available()
        else {}
    )
    __magic_name__        =		False
    __magic_name__        =		False
    __magic_name__        =		False
    __magic_name__        =		False
    def 		a_      (	self   ):
         snake_case					=    GPTNeoXJapaneseModelTester(self   )
         snake_case					=    ConfigTester(self      , config_class=__snake_case      , hidden_size=3_7   )
    def 		a_      (	self   ):
         self.config_tester.run_common_tests()
    def 		a_      (	self   ):
         snake_case			,  snake_case			,  snake_case			,  snake_case					=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(__snake_case      , __snake_case      , __snake_case   )
    def 		a_      (	self   ):
         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(__snake_case      , __snake_case      , __snake_case   )
    def 		a_      (	self   ):
         # 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(__snake_case      , __snake_case      , __snake_case   )
    def 		a_      (	self   ):
         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(__snake_case      , __snake_case      , __snake_case   )
    def 		a_      (	self   ):
         snake_case					=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_causal_lm(*__snake_case   )




    @slow
    def 		a_      (	self   ):
         snake_case					=    '''abeja/gpt-neox-japanese-2.7b'''

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

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

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

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




