





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

      """simple docstring"""


      def 			UpperCAmelCase_       (		self:			Optional[int]					):
          '''simple docstring'''


          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






      @property
      def 			UpperCAmelCase_       (		self:			str					):
          '''simple docstring'''


          UpperCamelCase__:	Any					=     1
          UpperCamelCase__:	List[Any]					=     3
          UpperCamelCase__:	Any					=     (32, 32)

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






      @property
      def 			UpperCAmelCase_       (		self:			List[Any]					):
          '''simple docstring'''


          torch.manual_seed(0					)
          UpperCamelCase__:	Optional[Any]					=     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 			UpperCAmelCase_       (		self:			int					):
          '''simple docstring'''


          torch.manual_seed(0					)
          UpperCamelCase__:	Any					=     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 			UpperCAmelCase_       (		self:			Optional[int]					):
          '''simple docstring'''


          torch.manual_seed(0					)
          UpperCamelCase__:	str					=     RobertaSeriesConfig(
              hidden_size=32	,    project_dim=32	,    intermediate_size=37	,    layer_norm_eps=1e-05	,    num_attention_heads=4	,    num_hidden_layers=5	,    pad_token_id=1	,    vocab_size=5006	,    )
          return RobertaSeriesModelWithTransformation(__lowerCamelCase					)






      @property
      def 			UpperCAmelCase_       (		self:			List[Any]					):
          '''simple docstring'''


          def extract(*__lowerCamelCase:			Optional[int]	,    **__lowerCamelCase:			Tuple					):




              class        _a    :

                    """simple docstring"""


                    def __init__(		self:			str					):
                        '''simple docstring'''


                        UpperCamelCase__:	List[str]					=     torch.ones([0]					)






                    def 			UpperCAmelCase_       (		self:			List[str]	,    __lowerCamelCase:			Tuple					):
                        '''simple docstring'''


                        self.pixel_values.to(__lowerCamelCase					)
                        return self
              return Out()

          return extract






      def 			UpperCAmelCase_       (		self:			Any					):
          '''simple docstring'''


          UpperCamelCase__:	Dict					=     "cpu"  # ensure determinism for the device-dependent torch.Generator
          UpperCamelCase__:	str					=     self.dummy_cond_unet
          UpperCamelCase__:	Tuple					=     PNDMScheduler(skip_prk_steps=__lowerCamelCase					)
          UpperCamelCase__:	List[str]					=     self.dummy_vae
          UpperCamelCase__:	List[str]					=     self.dummy_text_encoder
          UpperCamelCase__:	Dict					=     XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"					)
          UpperCamelCase__:	Optional[Any]					=     77

          UpperCamelCase__:	Dict					=     self.dummy_image.to(__lowerCamelCase					)
          UpperCamelCase__:	Optional[Any]					=     init_image / 2 + 0.5

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

          UpperCamelCase__:	Union[str, Any]					=     "A painting of a squirrel eating a burger"
          UpperCamelCase__:	List[str]					=     torch.Generator(device=__lowerCamelCase					).manual_seed(0					)
          UpperCamelCase__:	Tuple					=     alt_pipe(
              [prompt]	,    generator=__lowerCamelCase	,    guidance_scale=6.0	,    num_inference_steps=2	,    output_type="np"	,    image=__lowerCamelCase	,    )

          UpperCamelCase__:	Any					=     output.images

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

          UpperCamelCase__:	int					=     image[0, -3:, -3:, -1]
          UpperCamelCase__:	Union[str, Any]					=     image_from_tuple[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          UpperCamelCase__:	Optional[int]					=     np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499]					)

          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 			UpperCAmelCase_       (		self:			Any					):
          '''simple docstring'''


          UpperCamelCase__:	str					=     self.dummy_cond_unet
          UpperCamelCase__:	int					=     PNDMScheduler(skip_prk_steps=__lowerCamelCase					)
          UpperCamelCase__:	Union[str, Any]					=     self.dummy_vae
          UpperCamelCase__:	Dict					=     self.dummy_text_encoder
          UpperCamelCase__:	List[str]					=     XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"					)
          UpperCamelCase__:	int					=     77

          UpperCamelCase__:	Any					=     self.dummy_image.to(__lowerCamelCase					)

          # put models in fp16
          UpperCamelCase__:	Dict					=     unet.half()
          UpperCamelCase__:	int					=     vae.half()
          UpperCamelCase__:	Tuple					=     bert.half()

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

          UpperCamelCase__:	int					=     "A painting of a squirrel eating a burger"
          UpperCamelCase__:	Tuple					=     torch.manual_seed(0					)
          UpperCamelCase__:	Union[str, Any]					=     alt_pipe(
              [prompt]	,    generator=__lowerCamelCase	,    num_inference_steps=2	,    output_type="np"	,    image=__lowerCamelCase	,    ).images

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






      @unittest.skipIf(torch_device != "cuda"	,    "This test requires a GPU"					)
      def 			UpperCAmelCase_       (		self:			Any					):
          '''simple docstring'''


          UpperCamelCase__:	int					=     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
          UpperCamelCase__:	Tuple					=     init_image.resize((760, 504)					)

          UpperCamelCase__:	Tuple					=     "BAAI/AltDiffusion"
          UpperCamelCase__:	List[str]					=     AltDiffusionImgaImgPipeline.from_pretrained(
              __lowerCamelCase	,    safety_checker=__lowerCamelCase	,    )
          pipe.to(__lowerCamelCase					)
          pipe.set_progress_bar_config(disable=__lowerCamelCase					)
          pipe.enable_attention_slicing()

          UpperCamelCase__:	Dict					=     "A fantasy landscape, trending on artstation"

          UpperCamelCase__:	List[Any]					=     torch.manual_seed(0					)
          UpperCamelCase__:	Optional[int]					=     pipe(
              prompt=__lowerCamelCase	,    image=__lowerCamelCase	,    strength=0.75	,    guidance_scale=7.5	,    generator=__lowerCamelCase	,    output_type="np"	,    )
          UpperCamelCase__:	List[Any]					=     output.images[0]

          UpperCamelCase__:	List[str]					=     image[255:258, 383:386, -1]

          assert image.shape == (504, 760, 3)
          UpperCamelCase__:	Any					=     np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000]					)

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




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

      """simple docstring"""


      def 			UpperCAmelCase_       (		self:			int					):
          '''simple docstring'''


          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






      def 			UpperCAmelCase_       (		self:			List[Any]					):
          '''simple docstring'''


          UpperCamelCase__:	List[Any]					=     load_image(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
              "/img2img/sketch-mountains-input.jpg"					)
          UpperCamelCase__:	List[str]					=     init_image.resize((768, 512)					)
          UpperCamelCase__:	Tuple					=     load_numpy(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"					)

          UpperCamelCase__:	Tuple					=     "BAAI/AltDiffusion"
          UpperCamelCase__:	Optional[Any]					=     AltDiffusionImgaImgPipeline.from_pretrained(
              __lowerCamelCase	,    safety_checker=__lowerCamelCase	,    )
          pipe.to(__lowerCamelCase					)
          pipe.set_progress_bar_config(disable=__lowerCamelCase					)
          pipe.enable_attention_slicing()

          UpperCamelCase__:	Union[str, Any]					=     "A fantasy landscape, trending on artstation"

          UpperCamelCase__:	List[str]					=     torch.manual_seed(0					)
          UpperCamelCase__:	Optional[Any]					=     pipe(
              prompt=__lowerCamelCase	,    image=__lowerCamelCase	,    strength=0.75	,    guidance_scale=7.5	,    generator=__lowerCamelCase	,    output_type="np"	,    )
          UpperCamelCase__:	Dict					=     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








from typing import TYPE_CHECKING

from ...file_utils import _LazyModule, is_torch_available
from ...utils import OptionalDependencyNotAvailable


A__:    Any  	=	{
    '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''],
    '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   A__:    Union[str, Any]  	=	[
       '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''GPTNeoXJapaneseForCausalLM''',
       '''GPTNeoXJapaneseLayer''',
       '''GPTNeoXJapaneseModel''',
       '''GPTNeoXJapanesePreTrainedModel''',
   ]


if TYPE_CHECKING:
   from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig
   from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_gpt_neox_japanese import (
          GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
          GPTNeoXJapaneseForCausalLM,
          GPTNeoXJapaneseLayer,
          GPTNeoXJapaneseModel,
          GPTNeoXJapanesePreTrainedModel,
      )


else:
   import sys

   A__:    str  	=	_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

