


"""simple docstring"""




import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin


@skip_mps
class 	A_ (	__UpperCamelCase ,				__UpperCamelCase ,				unittest.TestCase   ):




      '''simple docstring'''


      __snake_case 	=       IFImgaImgSuperResolutionPipeline
      __snake_case 	=       TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""}
      __snake_case 	=       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""original_image"""}   )
      __snake_case 	=       PipelineTesterMixin.required_optional_params - {"""latents"""}




      def 					_snake_case     (    self:	Tuple    ):
       return self._get_superresolution_dummy_components()




      def 					_snake_case     (    self:	Dict						,				a:	Dict						,				a:	Optional[int]=0    ):


       if str(__UpperCAmelCase    ).startswith('mps'    ):
        __lowerCamelCase		:							Dict		 =						torch.manual_seed(__UpperCAmelCase    )
       else:
        __lowerCamelCase		:							str		 =						torch.Generator(device=__UpperCAmelCase    ).manual_seed(__UpperCAmelCase    )

       __lowerCamelCase		:							int		 =						floats_tensor((1, 3, 32, 32)						,				rng=random.Random(__UpperCAmelCase    )    ).to(__UpperCAmelCase    )
       __lowerCamelCase		:							Any		 =						floats_tensor((1, 3, 16, 16)						,				rng=random.Random(__UpperCAmelCase    )    ).to(__UpperCAmelCase    )

       __lowerCamelCase		:							Optional[Any]		 =						{
           'prompt': 'A painting of a squirrel eating a burger',
           'image': image,
           'original_image': original_image,
           'generator': generator,
           'num_inference_steps': 2,
           'output_type': 'numpy',
       }

       return inputs




      @unittest.skipIf(
          torch_device != 'cuda' or not is_xformers_available()						,				reason='XFormers attention is only available with CUDA and `xformers` installed'						,				)
      def 					_snake_case     (    self:	Tuple    ):
       self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3    )




      def 					_snake_case     (    self:	Optional[Any]    ):
       self._test_save_load_optional_components()




      @unittest.skipIf(torch_device != 'cuda'						,				reason='float16 requires CUDA'    )
      def 					_snake_case     (    self:	Union[str, Any]    ):
       super().test_save_load_floataa(expected_max_diff=1e-1    )




      def 					_snake_case     (    self:	Optional[Any]    ):
       self._test_attention_slicing_forward_pass(expected_max_diff=1e-2    )




      def 					_snake_case     (    self:	Optional[int]    ):
       self._test_save_load_local()




      def 					_snake_case     (    self:	Union[str, Any]    ):
       self._test_inference_batch_single_identical(
           expected_max_diff=1e-2						,				)





from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
       import torch

if is_torch_tpu_available(check_device=False):
       import torch_xla.core.xla_model as xm


lowercase_	   =     logging.get_logger(__name__)


@dataclass
class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [
          """no_inference""",
          """no_cuda""",
          """no_tpu""",
          """no_speed""",
          """no_memory""",
          """no_env_print""",
          """no_multi_process""",
      ]




      def __init__(    self:	Any						,				**a:	Optional[Any]    ):
       for deprecated_arg in self.deprecated_args:
        if deprecated_arg in kwargs:
         __lowerCamelCase		:							str		 =						deprecated_arg[3:]
         setattr(self						,				a						,				not kwargs.pop(a    )    )
         logger.warning(
             F'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or'
             F' {positive_arg}={kwargs[positive_arg]}'    )

       __lowerCamelCase		:							str		 =						kwargs.pop('torchscript'						,				self.torchscript    )
       __lowerCamelCase		:							int		 =						kwargs.pop('torch_xla_tpu_print_metrics'						,				self.torch_xla_tpu_print_metrics    )
       __lowerCamelCase		:							Dict		 =						kwargs.pop('fp16_opt_level'						,				self.fpaa_opt_level    )
       super().__init__(**a    )

      __snake_case 	=       field(default=__UpperCamelCase ,				metadata={"""help""": """Trace the models using torchscript"""}   )
      __snake_case 	=       field(default=__UpperCamelCase ,				metadata={"""help""": """Print Xla/PyTorch tpu metrics"""}   )
      __snake_case 	=       field(
          default="""O1""" ,				metadata={
              """help""": (
                  """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. """
                  """See details at https://nvidia.github.io/apex/amp.html"""
              )
          } ,				)




      @cached_property
      def 					_snake_case     (    self:	Dict    ):
       requires_backends(self						,				['torch']    )
       logger.info('PyTorch: setting up devices'    )
       if not self.cuda:
        __lowerCamelCase		:							Dict		 =						torch.device('cpu'    )
        __lowerCamelCase		:							str		 =						0
       elif is_torch_tpu_available():
        __lowerCamelCase		:							Optional[int]		 =						xm.xla_device()
        __lowerCamelCase		:							Dict		 =						0
       else:
        __lowerCamelCase		:							Any		 =						torch.device('cuda' if torch.cuda.is_available() else 'cpu'    )
        __lowerCamelCase		:							Union[str, Any]		 =						torch.cuda.device_count()
       return device, n_gpu




      @property
      def 					_snake_case     (    self:	Optional[Any]    ):
       return is_torch_tpu_available() and self.tpu




      @property
      def 					_snake_case     (    self:	Union[str, Any]    ):
       requires_backends(self						,				['torch']    )
       # TODO(PVP): currently only single GPU is supported
       return torch.cuda.current_device()




      @property
      def 					_snake_case     (    self:	int    ):
       requires_backends(self						,				['torch']    )
       return self._setup_devices[0]




      @property
      def 					_snake_case     (    self:	Union[str, Any]    ):
       requires_backends(self						,				['torch']    )
       return self._setup_devices[1]




      @property
      def 					_snake_case     (    self:	List[Any]    ):
       return self.n_gpu > 0

