

'''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						,			UpperCamelCase__						,			UpperCamelCase__=13						,			UpperCamelCase__=7						,			UpperCamelCase__=True						,			UpperCamelCase__=True						,			UpperCamelCase__=True						,			UpperCamelCase__=True						,			UpperCamelCase__=99						,			UpperCamelCase__=32						,			UpperCamelCase__=5						,			UpperCamelCase__=4						,			UpperCamelCase__=4						,			UpperCamelCase__="gelu"						,			UpperCamelCase__=0.0						,			UpperCamelCase__=0.1						,			UpperCamelCase__=True						,			UpperCamelCase__=512						,			UpperCamelCase__=16						,			UpperCamelCase__=2						,			UpperCamelCase__=0.02						,			UpperCamelCase__=3						,			UpperCamelCase__=4						,			UpperCamelCase__=None						,			)  -> Any:





           '''simple docstring'''
           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    )  -> str:





           '''simple docstring'''
           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    )  -> str:





           '''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    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           A_   ,     A_   ,     A_   ,     A_		   = self.prepare_config_and_inputs()

           A_		   = True

           return config, input_ids, input_mask, token_labels



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Tuple:





           '''simple docstring'''
           A_		   = GPTNeoXJapaneseModel(config=UpperCamelCase__    )
           model.to(UpperCamelCase__    )
           model.eval()
           A_		   = model(UpperCamelCase__						,			attention_mask=UpperCamelCase__    )
           A_		   = model(UpperCamelCase__    )
           self.parent.assertEqual(result.last_hidden_state.shape						,			(self.batch_size, self.seq_length, self.hidden_size)    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> str:





           '''simple docstring'''
           A_		   = True
           A_		   = GPTNeoXJapaneseModel(UpperCamelCase__    )
           model.to(UpperCamelCase__    )
           model.eval()
           A_		   = model(UpperCamelCase__						,			attention_mask=UpperCamelCase__    )
           self.parent.assertEqual(result.last_hidden_state.shape						,			(self.batch_size, self.seq_length, self.hidden_size)    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> List[str]:





           '''simple docstring'''
           A_		   = GPTNeoXJapaneseForCausalLM(config=UpperCamelCase__    )
           model.to(UpperCamelCase__    )
           model.eval()
           A_		   = model(UpperCamelCase__						,			attention_mask=UpperCamelCase__						,			labels=UpperCamelCase__    )
           self.parent.assertEqual(result.logits.shape						,			(self.batch_size, self.seq_length, self.vocab_size)    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Union[str, Any]:





           '''simple docstring'''
           A_		   = True
           A_		   = GPTNeoXJapaneseForCausalLM(config=UpperCamelCase__    )
           model.to(UpperCamelCase__    )
           model.eval()

           # first forward pass
           A_		   = model(UpperCamelCase__						,			attention_mask=UpperCamelCase__						,			use_cache=UpperCamelCase__    )
           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(UpperCamelCase__						,			attention_mask=UpperCamelCase__						,			output_hidden_states=UpperCamelCase__    )
           A_		   = output_from_no_past["""hidden_states"""][0]
           A_		   = model(
               UpperCamelCase__						,			attention_mask=UpperCamelCase__						,			past_key_values=UpperCamelCase__						,			output_hidden_states=UpperCamelCase__						,			)["""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(UpperCamelCase__						,			UpperCamelCase__						,			atol=1e-3    )    )







    def    snake_case_     (   self    )  -> Union[str, Any]:





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


@require_torch
class    A__ ( _snake_case  ,  _snake_case  ,  unittest.TestCase     ):
    lowercase		   =						(GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
    lowercase		   =						(GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
    lowercase		   =						(
        {"feature-extraction": GPTNeoXJapaneseModel, "text-generation": GPTNeoXJapaneseForCausalLM}
        if is_torch_available()
        else {}
    )
    lowercase		   =						False
    lowercase		   =						False
    lowercase		   =						False
    lowercase		   =						False



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





           '''simple docstring'''
           A_		   = GPTNeoXJapaneseModelTester(self    )
           A_		   = ConfigTester(self						,			config_class=UpperCamelCase__						,			hidden_size=37    )



    def    snake_case_     (   self    )  -> Tuple:





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



    def    snake_case_     (   self    )  -> int:





           '''simple docstring'''
           A_   ,     A_   ,     A_   ,     A_		   = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )



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





           '''simple docstring'''
           A_   ,     A_   ,     A_   ,     A_		   = self.model_tester.prepare_config_and_inputs_for_decoder()
           self.model_tester.create_and_check_model_as_decoder(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )



    def    snake_case_     (   self    )  -> Any:





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

           A_		   = None

           self.model_tester.create_and_check_model_as_decoder(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )



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





           '''simple docstring'''
           A_   ,     A_   ,     A_   ,     A_		   = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_decoder_model_past_large_inputs(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )



    def    snake_case_     (   self    )  -> int:





           '''simple docstring'''
           A_		   = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_causal_lm(*UpperCamelCase__    )







    @slow
    def    snake_case_     (   self    )  -> Optional[int]:





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

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

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

           A_		   = GPTNeoXJapaneseTokenizer.from_pretrained(UpperCamelCase__    )
           A_		   = GPTNeoXJapaneseForCausalLM.from_pretrained(UpperCamelCase__    )

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



'''simple docstring'''







import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()


class    A__ ( unittest.TestCase     ):



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





           '''simple docstring'''
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



    @property
    def    snake_case_     (   self    )  -> List[str]:





           '''simple docstring'''
           A_		   = 1
           A_		   = 3
           A_		   = (32, 32)

           A_		   = floats_tensor((batch_size, num_channels) + sizes						,			rng=random.Random(0    )    ).to(UpperCamelCase__    )
           return image



    @property
    def    snake_case_     (   self    )  -> Union[str, Any]:





           '''simple docstring'''
           torch.manual_seed(0    )
           A_		   = UNetaDConditionModel(
               block_out_channels=(32, 64)						,			layers_per_block=2						,			sample_size=32						,			in_channels=4						,			out_channels=4						,			down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")						,			up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")						,			cross_attention_dim=32						,			)
           return model



    @property
    def    snake_case_     (   self    )  -> List[str]:





           '''simple docstring'''
           torch.manual_seed(0    )
           A_		   = AutoencoderKL(
               block_out_channels=[32, 64]						,			in_channels=3						,			out_channels=3						,			down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]						,			up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]						,			latent_channels=4						,			)
           return model



    @property
    def    snake_case_     (   self    )  -> List[Any]:





           '''simple docstring'''
           torch.manual_seed(0    )
           A_		   = RobertaSeriesConfig(
               hidden_size=32						,			project_dim=32						,			intermediate_size=37						,			layer_norm_eps=1e-0_5						,			num_attention_heads=4						,			num_hidden_layers=5						,			pad_token_id=1						,			vocab_size=5006						,			)
           return RobertaSeriesModelWithTransformation(UpperCamelCase__    )



    @property
    def    snake_case_     (   self    )  -> int:





           '''simple docstring'''
           def extract(*UpperCamelCase__						,			**UpperCamelCase__    ):


                  class    A__ :



                      def __init__(   self    )  -> Dict:





                             '''simple docstring'''
                             A_		   = torch.ones([0]    )







                      def    snake_case_     (   self						,			UpperCamelCase__    )  -> str:





                             '''simple docstring'''
                             self.pixel_values.to(UpperCamelCase__    )
                             return self

                  return Out()

           return extract



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





           '''simple docstring'''
           A_		   = """cpu"""  # ensure determinism for the device-dependent torch.Generator
           A_		   = self.dummy_cond_unet
           A_		   = PNDMScheduler(skip_prk_steps=UpperCamelCase__    )
           A_		   = self.dummy_vae
           A_		   = self.dummy_text_encoder
           A_		   = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""    )
           A_		   = 77

           A_		   = self.dummy_image.to(UpperCamelCase__    )
           A_		   = init_image / 2 + 0.5

           # make sure here that pndm scheduler skips prk
           A_		   = AltDiffusionImgaImgPipeline(
               unet=UpperCamelCase__						,			scheduler=UpperCamelCase__						,			vae=UpperCamelCase__						,			text_encoder=UpperCamelCase__						,			tokenizer=UpperCamelCase__						,			safety_checker=UpperCamelCase__						,			feature_extractor=self.dummy_extractor						,			)
           A_		   = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						,			do_normalize=UpperCamelCase__    )
           A_		   = alt_pipe.to(UpperCamelCase__    )
           alt_pipe.set_progress_bar_config(disable=UpperCamelCase__    )

           A_		   = """A painting of a squirrel eating a burger"""
           A_		   = torch.Generator(device=UpperCamelCase__    ).manual_seed(0    )
           A_		   = alt_pipe(
               [prompt]						,			generator=UpperCamelCase__						,			guidance_scale=6.0						,			num_inference_steps=2						,			output_type="""np"""						,			image=UpperCamelCase__						,			)

           A_		   = output.images

           A_		   = torch.Generator(device=UpperCamelCase__    ).manual_seed(0    )
           A_		   = alt_pipe(
               [prompt]						,			generator=UpperCamelCase__						,			guidance_scale=6.0						,			num_inference_steps=2						,			output_type="""np"""						,			image=UpperCamelCase__						,			return_dict=UpperCamelCase__						,			)[0]

           A_		   = image[0, -3:, -3:, -1]
           A_		   = image_from_tuple[0, -3:, -3:, -1]

           assert image.shape == (1, 32, 32, 3)
           A_		   = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]    )

           assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5e-3
           assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 5e-3



    @unittest.skipIf(torch_device != """cuda"""						,			"""This test requires a GPU"""    )
    def    snake_case_     (   self    )  -> Union[str, Any]:





           '''simple docstring'''
           A_		   = self.dummy_cond_unet
           A_		   = PNDMScheduler(skip_prk_steps=UpperCamelCase__    )
           A_		   = self.dummy_vae
           A_		   = self.dummy_text_encoder
           A_		   = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""    )
           A_		   = 77

           A_		   = self.dummy_image.to(UpperCamelCase__    )

           # put models in fp16
           A_		   = unet.half()
           A_		   = vae.half()
           A_		   = bert.half()

           # make sure here that pndm scheduler skips prk
           A_		   = AltDiffusionImgaImgPipeline(
               unet=UpperCamelCase__						,			scheduler=UpperCamelCase__						,			vae=UpperCamelCase__						,			text_encoder=UpperCamelCase__						,			tokenizer=UpperCamelCase__						,			safety_checker=UpperCamelCase__						,			feature_extractor=self.dummy_extractor						,			)
           A_		   = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						,			do_normalize=UpperCamelCase__    )
           A_		   = alt_pipe.to(UpperCamelCase__    )
           alt_pipe.set_progress_bar_config(disable=UpperCamelCase__    )

           A_		   = """A painting of a squirrel eating a burger"""
           A_		   = torch.manual_seed(0    )
           A_		   = alt_pipe(
               [prompt]						,			generator=UpperCamelCase__						,			num_inference_steps=2						,			output_type="""np"""						,			image=UpperCamelCase__						,			).images

           assert image.shape == (1, 32, 32, 3)







    @unittest.skipIf(torch_device != """cuda"""						,			"""This test requires a GPU"""    )
    def    snake_case_     (   self    )  -> Any:





           '''simple docstring'''
           A_		   = load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/img2img/sketch-mountains-input.jpg"""    )
           # resize to resolution that is divisible by 8 but not 16 or 32
           A_		   = init_image.resize((760, 504)    )

           A_		   = """BAAI/AltDiffusion"""
           A_		   = AltDiffusionImgaImgPipeline.from_pretrained(
               UpperCamelCase__						,			safety_checker=UpperCamelCase__						,			)
           pipe.to(UpperCamelCase__    )
           pipe.set_progress_bar_config(disable=UpperCamelCase__    )
           pipe.enable_attention_slicing()

           A_		   = """A fantasy landscape, trending on artstation"""

           A_		   = torch.manual_seed(0    )
           A_		   = pipe(
               prompt=UpperCamelCase__						,			image=UpperCamelCase__						,			strength=0.75						,			guidance_scale=7.5						,			generator=UpperCamelCase__						,			output_type="""np"""						,			)
           A_		   = output.images[0]

           A_		   = image[255:258, 383:386, -1]

           assert image.shape == (504, 760, 3)
           A_		   = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]    )

           assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2


@slow
@require_torch_gpu
class    A__ ( unittest.TestCase     ):



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





           '''simple docstring'''
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()







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





           '''simple docstring'''
           A_		   = load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/img2img/sketch-mountains-input.jpg"""    )
           A_		   = init_image.resize((768, 512)    )
           A_		   = load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""    )

           A_		   = """BAAI/AltDiffusion"""
           A_		   = AltDiffusionImgaImgPipeline.from_pretrained(
               UpperCamelCase__						,			safety_checker=UpperCamelCase__						,			)
           pipe.to(UpperCamelCase__    )
           pipe.set_progress_bar_config(disable=UpperCamelCase__    )
           pipe.enable_attention_slicing()

           A_		   = """A fantasy landscape, trending on artstation"""

           A_		   = torch.manual_seed(0    )
           A_		   = pipe(
               prompt=UpperCamelCase__						,			image=UpperCamelCase__						,			strength=0.75						,			guidance_scale=7.5						,			generator=UpperCamelCase__						,			output_type="""np"""						,			)
           A_		   = output.images[0]

           assert image.shape == (512, 768, 3)
           # img2img is flaky across GPUs even in fp32, so using MAE here
           assert np.abs(expected_image - image    ).max() < 1e-2
