
"""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 			_SCREAMING_SNAKE_CASE					(			unittest.TestCase							):






			def  __lowerCAmelCase (					self       )			->     str:
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()






			@property
			def  __lowerCAmelCase (					self       )			->     Union[str, Any]:
						lowerCAmelCase_    :Union[str, Any]			     =  1
						lowerCAmelCase_    :Any			     =  3
						lowerCAmelCase_    :Tuple			     =  (32, 32)

						lowerCAmelCase_    :Dict			     =  floats_tensor((batch_size, num_channels) + sizes       ,   rng=random.Random(0       )       ).to(__A       )
						return image






			@property
			def  __lowerCAmelCase (					self       )			->     Any:
						torch.manual_seed(0       )
						lowerCAmelCase_    :Dict			     =  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  __lowerCAmelCase (					self       )			->     List[Any]:
						torch.manual_seed(0       )
						lowerCAmelCase_    :Optional[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  __lowerCAmelCase (					self       )			->     Tuple:
						torch.manual_seed(0       )
						lowerCAmelCase_    :Optional[Any]			     =  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(__A       )






			@property
			def  __lowerCAmelCase (					self       )			->     int:
						def extract(*__A       ,   **__A       ):




									class 			_SCREAMING_SNAKE_CASE					:






												def __init__(					self       )			->     str:
															lowerCAmelCase_    :List[str]			     =  torch.ones([0]       )






												def  __lowerCAmelCase (					self       ,   __A       )			->     int:
															self.pixel_values.to(__A       )
															return self




									return Out()

						return extract






			def  __lowerCAmelCase (					self       )			->     str:
						lowerCAmelCase_    :List[str]			     =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
						lowerCAmelCase_    :Dict			     =  self.dummy_cond_unet
						lowerCAmelCase_    :List[Any]			     =  PNDMScheduler(skip_prk_steps=__A       )
						lowerCAmelCase_    :int			     =  self.dummy_vae
						lowerCAmelCase_    :Union[str, Any]			     =  self.dummy_text_encoder
						lowerCAmelCase_    :Optional[int]			     =  XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""       )
						lowerCAmelCase_    :Dict			     =  77

						lowerCAmelCase_    :Tuple			     =  self.dummy_image.to(__A       )
						lowerCAmelCase_    :Any			     =  init_image / 2 + 0.5

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

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

						lowerCAmelCase_    :Tuple			     =  output.images

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

						lowerCAmelCase_    :Tuple			     =  image[0, -3:, -3:, -1]
						lowerCAmelCase_    :List[str]			     =  image_from_tuple[0, -3:, -3:, -1]

						assert image.shape == (1, 32, 32, 3)
						lowerCAmelCase_    :str			     =  np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9]       )

						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  __lowerCAmelCase (					self       )			->     Optional[int]:
						lowerCAmelCase_    :Tuple			     =  self.dummy_cond_unet
						lowerCAmelCase_    :int			     =  PNDMScheduler(skip_prk_steps=__A       )
						lowerCAmelCase_    :int			     =  self.dummy_vae
						lowerCAmelCase_    :Dict			     =  self.dummy_text_encoder
						lowerCAmelCase_    :List[Any]			     =  XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""       )
						lowerCAmelCase_    :Optional[Any]			     =  77

						lowerCAmelCase_    :Optional[int]			     =  self.dummy_image.to(__A       )

						# put models in fp16
						lowerCAmelCase_    :Any			     =  unet.half()
						lowerCAmelCase_    :Union[str, Any]			     =  vae.half()
						lowerCAmelCase_    :Optional[Any]			     =  bert.half()

						# make sure here that pndm scheduler skips prk
						lowerCAmelCase_    :Tuple			     =  AltDiffusionImgaImgPipeline(
						    unet=__A       ,   scheduler=__A       ,   vae=__A       ,   text_encoder=__A       ,   tokenizer=__A       ,   safety_checker=__A       ,   feature_extractor=self.dummy_extractor       ,   )
						lowerCAmelCase_    :List[str]			     =  VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor       ,   do_normalize=__A       )
						lowerCAmelCase_    :Union[str, Any]			     =  alt_pipe.to(__A       )
						alt_pipe.set_progress_bar_config(disable=__A       )

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

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






			@unittest.skipIf(torch_device != """cuda"""       ,   """This test requires a GPU"""       )
			def  __lowerCAmelCase (					self       )			->     Optional[int]:
						lowerCAmelCase_    :List[str]			     =  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
						lowerCAmelCase_    :Tuple			     =  init_image.resize((760, 504)       )

						lowerCAmelCase_    :str			     =  """BAAI/AltDiffusion"""
						lowerCAmelCase_    :str			     =  AltDiffusionImgaImgPipeline.from_pretrained(
						    __A       ,   safety_checker=__A       ,   )
						pipe.to(__A       )
						pipe.set_progress_bar_config(disable=__A       )
						pipe.enable_attention_slicing()

						lowerCAmelCase_    :Any			     =  """A fantasy landscape, trending on artstation"""

						lowerCAmelCase_    :Dict			     =  torch.manual_seed(0       )
						lowerCAmelCase_    :str			     =  pipe(
						    prompt=__A       ,   image=__A       ,   strength=0.7_5       ,   guidance_scale=7.5       ,   generator=__A       ,   output_type="""np"""       ,   )
						lowerCAmelCase_    :Dict			     =  output.images[0]

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

						assert image.shape == (504, 760, 3)
						lowerCAmelCase_    :int			     =  np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0]       )

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




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






			def  __lowerCAmelCase (					self       )			->     Tuple:
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()






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

						lowerCAmelCase_    :Union[str, Any]			     =  """BAAI/AltDiffusion"""
						lowerCAmelCase_    :Any			     =  AltDiffusionImgaImgPipeline.from_pretrained(
						    __A       ,   safety_checker=__A       ,   )
						pipe.to(__A       )
						pipe.set_progress_bar_config(disable=__A       )
						pipe.enable_attention_slicing()

						lowerCAmelCase_    :Tuple			     =  """A fantasy landscape, trending on artstation"""

						lowerCAmelCase_    :int			     =  torch.manual_seed(0       )
						lowerCAmelCase_    :Tuple			     =  pipe(
						    prompt=__A       ,   image=__A       ,   strength=0.7_5       ,   guidance_scale=7.5       ,   generator=__A       ,   output_type="""np"""       ,   )
						lowerCAmelCase_    :Optional[int]			     =  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 dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
					import tensorflow as tf


UpperCamelCase__    			=			logging.get_logger(__name__)
@dataclass
class 			a__    (					snake_case__      ):
						_a							:    List[str]					=    [
						    """no_inference""",
						    """no_cuda""",
						    """no_tpu""",
						    """no_speed""",
						    """no_memory""",
						    """no_env_print""",
						    """no_multi_process""",
						]






						def __init__(   self		,			**_A			):




											"""simple docstring"""



											for deprecated_arg in self.deprecated_args:
																if deprecated_arg in kwargs:
																					__lowerCAmelCase				   =       deprecated_arg[3:]
																					__lowerCAmelCase				   =       not kwargs.pop(_A			)
																					logger.warning(
																					    f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or"""
																					    f""" {positive_arg}={kwargs[positive_arg]}"""			)
											__lowerCAmelCase				   =       kwargs.pop("tpu_name"		,			self.tpu_name			)
											__lowerCAmelCase				   =       kwargs.pop("device_idx"		,			self.device_idx			)
											__lowerCAmelCase				   =       kwargs.pop("eager_mode"		,			self.eager_mode			)
											__lowerCAmelCase				   =       kwargs.pop("use_xla"		,			self.use_xla			)
											super().__init__(**_A			)

						_a							:    str					=    field(
						    default=snake_case__ ,				metadata={"""help""": """Name of TPU"""} ,				)
						_a							:    int					=    field(
						    default=0 ,				metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} ,				)
						_a							:    bool					=    field(default=snake_case__ ,				metadata={"""help""": """Benchmark models in eager model."""}      )
						_a							:    bool					=    field(
						    default=snake_case__ ,				metadata={
						        """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`."""
						    } ,				)






						@cached_property
						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											requires_backends(self		,			["tf"]			)
											__lowerCAmelCase				   =       None
											if self.tpu:
																try:
																					if self.tpu_name:
																										__lowerCAmelCase				   =       tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name			)
																					else:
																										__lowerCAmelCase				   =       tf.distribute.cluster_resolver.TPUClusterResolver()
																except ValueError:
																					__lowerCAmelCase				   =       None
											return tpu






						@cached_property
						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											requires_backends(self		,			["tf"]			)
											if self.is_tpu:
																tf.config.experimental_connect_to_cluster(self._setup_tpu			)
																tf.tpu.experimental.initialize_tpu_system(self._setup_tpu			)

																__lowerCAmelCase				   =       tf.distribute.TPUStrategy(self._setup_tpu			)
											else:
																# currently no multi gpu is allowed
																if self.is_gpu:
																					# TODO: Currently only single GPU is supported
																					tf.config.set_visible_devices(self.gpu_list[self.device_idx]		,			"GPU"			)
																					__lowerCAmelCase				   =       tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}"""			)
																else:
																					tf.config.set_visible_devices([]		,			"GPU"			)  # disable GPU
																					__lowerCAmelCase				   =       tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}"""			)

											return strategy






						@property
						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											requires_backends(self		,			["tf"]			)
											return self._setup_tpu is not None






						@property
						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											requires_backends(self		,			["tf"]			)
											return self._setup_strategy






						@property
						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											requires_backends(self		,			["tf"]			)
											return tf.config.list_physical_devices("GPU"			)






						@property
						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											requires_backends(self		,			["tf"]			)
											if self.cuda:
																return len(self.gpu_list			)
											return 0






						@property
						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											return self.n_gpu > 0




