import importlib
import importlib.metadata
import os
import warnings
from distutils.util import strtobool
from functools import lru_cache

import torch
from packaging import version
from packaging.version import parse

from .environment import parse_flag_from_env
from .versions import compare_versions, is_torch_version


try:
     import torch_xla.core.xla_model as xm  # noqa: F401

     __snake_case         =     True
except ImportError:
     __snake_case         =     False


# Cache this result has it's a C FFI call which can be pretty time-consuming
__snake_case         =     torch.distributed.is_available()





def 	lowerCAmelCase_			(					__lowerCAmelCase    )->	int:






      '''simple docstring'''





      UpperCAmelCase     :			Optional[Any]     	=importlib.util.find_spec(__lowercase    ) is not None
      if package_exists:
            try:
                  UpperCAmelCase     :			Optional[int]     	=importlib.metadata.metadata(__lowercase    )
                  return True
            except importlib.metadata.PackageNotFoundError:
                  return False





def 	lowerCAmelCase_			(					)->	Optional[Any]:






      '''simple docstring'''





      return _torch_distributed_available





def 	lowerCAmelCase_			(					)->	str:






      '''simple docstring'''





      try:
            pass
      except ImportError:
            print(
                '''Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not'''
                ''' detected. If you see \"ValueError: Invalid backend: \'ccl\'\" error, please install Intel(R) oneCCL'''
                ''' Bindings for PyTorch*.'''    )
      return (
          importlib.util.find_spec('''torch_ccl'''    ) is not None
          or importlib.util.find_spec('''oneccl_bindings_for_pytorch'''    ) is not None
      )





def 	lowerCAmelCase_			(					)->	Tuple:






      '''simple docstring'''





      return importlib.metadata.version('''oneccl_bind_pt'''    )





def 	lowerCAmelCase_			(					)->	Tuple:






      '''simple docstring'''





      return _is_package_available('''transformer_engine'''    )





@lru_cache
def 	lowerCAmelCase_			(					__lowerCAmelCase=True    )->	List[str]:






      '''simple docstring'''





      if torch.cuda.is_available():
            return False
      if _tpu_available and check_device:
            try:
                  # Will raise a RuntimeError if no XLA configuration is found
                  UpperCAmelCase     :			Union[str, Any]     	=xm.xla_device()
                  return True
            except RuntimeError:
                  return False
      return _tpu_available





def 	lowerCAmelCase_			(					)->	List[Any]:






      '''simple docstring'''





      return _is_package_available('''deepspeed'''    )





def 	lowerCAmelCase_			(					__lowerCAmelCase=False    )->	int:






      '''simple docstring'''





      if is_tpu_available():
            return not ignore_tpu
      if torch.cuda.is_available():
            return torch.cuda.is_bfaa_supported()
      if is_npu_available():
            return False
      return True





def 	lowerCAmelCase_			(					)->	Any:






      '''simple docstring'''





      UpperCAmelCase     :			Optional[Any]     	=_is_package_available('''bitsandbytes'''    )
      if package_exists:
            UpperCAmelCase     :			Dict     	=version.parse(importlib.metadata.version('''bitsandbytes'''    )    )
            return compare_versions(__lowercase		,       '''>='''		,       '''0.39.0'''    )
      return False





def 	lowerCAmelCase_			(					)->	List[Any]:






      '''simple docstring'''





      UpperCAmelCase     :			List[str]     	=_is_package_available('''bitsandbytes'''    )
      if package_exists:
            UpperCAmelCase     :			Dict     	=version.parse(importlib.metadata.version('''bitsandbytes'''    )    )
            return compare_versions(__lowercase		,       '''>='''		,       '''0.37.2'''    )
      return False





def 	lowerCAmelCase_			(					)->	List[str]:






      '''simple docstring'''





      return _is_package_available('''bitsandbytes'''    )





def 	lowerCAmelCase_			(					)->	Tuple:






      '''simple docstring'''





      if strtobool(os.environ.get('''ACCELERATE_USE_MEGATRON_LM'''		,       '''False'''    )    ) == 1:
            UpperCAmelCase     :			Union[str, Any]     	=importlib.util.find_spec('''megatron'''    ) is not None
            if package_exists:
                  try:
                        UpperCAmelCase     :			str     	=parse(importlib.metadata.version('''megatron-lm'''    )    )
                        return compare_versions(__lowercase		,       '''>='''		,       '''2.2.0'''    )
                  except Exception as e:
                        warnings.warn(f'''Parse Megatron version failed. Exception:{e}'''    )
                        return False





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






      '''simple docstring'''





      return _is_package_available('''safetensors'''    )





def 	lowerCAmelCase_			(					)->	int:






      '''simple docstring'''





      return _is_package_available('''transformers'''    )





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






      '''simple docstring'''





      return _is_package_available('''datasets'''    )





def 	lowerCAmelCase_			(					)->	Dict:






      '''simple docstring'''





      return _is_package_available('''aim'''    )





def 	lowerCAmelCase_			(					)->	Tuple:






      '''simple docstring'''





      return _is_package_available('''tensorboard'''    ) or _is_package_available('''tensorboardX'''    )





def 	lowerCAmelCase_			(					)->	Tuple:






      '''simple docstring'''





      return _is_package_available('''wandb'''    )





def 	lowerCAmelCase_			(					)->	List[Any]:






      '''simple docstring'''





      return _is_package_available('''comet_ml'''    )





def 	lowerCAmelCase_			(					)->	int:






      '''simple docstring'''





      return _is_package_available('''boto3'''    )





def 	lowerCAmelCase_			(					)->	Any:






      '''simple docstring'''





      if _is_package_available('''rich'''    ):
            if "ACCELERATE_DISABLE_RICH" in os.environ:
                  warnings.warn(
                      '''`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`.'''    )
                  return not parse_flag_from_env('''ACCELERATE_DISABLE_RICH'''		,       __lowercase    )
            return parse_flag_from_env('''ACCELERATE_ENABLE_RICH'''		,       __lowercase    )
      return False





def 	lowerCAmelCase_			(					)->	Tuple:






      '''simple docstring'''





      return _is_package_available('''sagemaker'''    )





def 	lowerCAmelCase_			(					)->	List[Any]:






      '''simple docstring'''





      return _is_package_available('''tqdm'''    )





def 	lowerCAmelCase_			(					)->	Dict:






      '''simple docstring'''





      return _is_package_available('''mlflow'''    )





def 	lowerCAmelCase_			(					)->	Optional[Any]:






      '''simple docstring'''





      return is_torch_version('''>='''		,       '''1.12'''    ) and torch.backends.mps.is_available() and torch.backends.mps.is_built()





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






      '''simple docstring'''





      def get_major_and_minor_from_version(__lowerCAmelCase    ):
            return str(version.parse(__lowercase    ).major    ) + "." + str(version.parse(__lowercase    ).minor    )

      UpperCAmelCase     :			int     	=importlib.metadata.version('''torch'''    )
      if importlib.util.find_spec('''intel_extension_for_pytorch'''    ) is None:
            return False
      UpperCAmelCase     :			Optional[Any]     	='''N/A'''
      try:
            UpperCAmelCase     :			List[Any]     	=importlib.metadata.version('''intel_extension_for_pytorch'''    )
      except importlib.metadata.PackageNotFoundError:
            return False
      UpperCAmelCase     :			Optional[int]     	=get_major_and_minor_from_version(_torch_version    )
      UpperCAmelCase     :			Optional[Any]     	=get_major_and_minor_from_version(_ipex_version    )
      if torch_major_and_minor != ipex_major_and_minor:
            warnings.warn(
                f'''Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,'''
                f''' but PyTorch {_torch_version} is found. Please switch to the matching version and run again.'''    )
            return False
      return True





@lru_cache
def 	lowerCAmelCase_			(					__lowerCAmelCase=False    )->	Optional[int]:






      '''simple docstring'''





      if importlib.util.find_spec('''torch'''    ) is None or importlib.util.find_spec('''torch_npu'''    ) is None:
            return False

      import torch
      import torch_npu  # noqa: F401

      if check_device:
            try:
                  # Will raise a RuntimeError if no NPU is found
                  UpperCAmelCase     :			Tuple     	=torch.npu.device_count()
                  return torch.npu.is_available()
            except RuntimeError:
                  return False
      return hasattr(__lowercase		,       '''npu'''    ) and torch.npu.is_available()





@lru_cache
def 	lowerCAmelCase_			(					__lowerCAmelCase=False    )->	Any:






      '''simple docstring'''





      if not parse_flag_from_env('''ACCELERATE_USE_XPU'''		,       default=__lowercase    ):
            return False
      if is_ipex_available():
            import torch

            if is_torch_version('''<='''		,       '''1.12'''    ):
                  return False
      else:
            return False

      import intel_extension_for_pytorch  # noqa: F401

      if check_device:
            try:
                  # Will raise a RuntimeError if no XPU  is found
                  UpperCAmelCase     :			Optional[Any]     	=torch.xpu.device_count()
                  return torch.xpu.is_available()
            except RuntimeError:
                  return False
      return hasattr(__lowercase		,       '''xpu'''    ) and torch.xpu.is_available()




import gc
import unittest

import numpy as np
import torch

from diffusers import RePaintPipeline, RePaintScheduler, UNetaDModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_image,
    load_numpy,
    nightly,
    require_torch_gpu,
    skip_mps,
    torch_device,
)

from ..pipeline_params import IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class 			lowerCAmelCase__(     snake_case__     ,     unittest.TestCase    ):






    '''simple docstring'''





    A_	:  Tuple								=			RePaintPipeline
    A_	:  Tuple								=			IMAGE_INPAINTING_PARAMS - {'width', 'height', 'guidance_scale'}
    A_	:  str								=			PipelineTesterMixin.required_optional_params - {
        'latents',
        'num_images_per_prompt',
        'callback',
        'callback_steps',
    }
    A_	:  Optional[Any]								=			IMAGE_INPAINTING_BATCH_PARAMS
    A_	:  Union[str, Any]								=			False





    def        _lowerCamelCase			(						self					: Any						):





       '''simple docstring'''
       torch.manual_seed(0						)
       torch.manual_seed(0						)
       UpperCAmelCase_				:   int							= UNetaDModel(
           block_out_channels=(32, 64)							, layers_per_block=2							, sample_size=32							, in_channels=3							, out_channels=3							, down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')							, up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')							, )
       UpperCAmelCase_				:   str							= RePaintScheduler()
       UpperCAmelCase_				:   Optional[Any]							= {'''unet''': unet, '''scheduler''': scheduler}
       return components





    def        _lowerCamelCase			(						self					: List[str]							, __snake_case					: Optional[Any]							, __snake_case					: int=0						):





       '''simple docstring'''
       if str(__snake_case						).startswith('''mps'''						):
          UpperCAmelCase_				:   Optional[Any]							= torch.manual_seed(__snake_case						)
       else:
          UpperCAmelCase_				:   Optional[Any]							= torch.Generator(device=__snake_case						).manual_seed(__snake_case						)
       UpperCAmelCase_				:   Optional[Any]							= np.random.RandomState(__snake_case						).standard_normal((1, 3, 32, 32)						)
       UpperCAmelCase_				:   Optional[int]							= torch.from_numpy(__snake_case						).to(device=__snake_case							, dtype=torch.floataa						)
       UpperCAmelCase_				:   Any							= (image > 0).to(device=__snake_case							, dtype=torch.floataa						)
       UpperCAmelCase_				:   List[str]							= {
           '''image''': image,
           '''mask_image''': mask,
           '''generator''': generator,
           '''num_inference_steps''': 5,
           '''eta''': 0.0,
           '''jump_length''': 2,
           '''jump_n_sample''': 2,
           '''output_type''': '''numpy''',
       }
       return inputs





    def        _lowerCamelCase			(						self					: Union[str, Any]						):





       '''simple docstring'''
       UpperCAmelCase_				:   str							= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       UpperCAmelCase_				:   Optional[int]							= self.get_dummy_components()
       UpperCAmelCase_				:   Dict							= RePaintPipeline(**__snake_case						)
       UpperCAmelCase_				:   int							= sd_pipe.to(__snake_case						)
       sd_pipe.set_progress_bar_config(disable=__snake_case						)

       UpperCAmelCase_				:   List[Any]							= self.get_dummy_inputs(__snake_case						)
       UpperCAmelCase_				:   Union[str, Any]							= sd_pipe(**__snake_case						).images
       UpperCAmelCase_				:   Optional[Any]							= image[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       UpperCAmelCase_				:   Tuple							= np.array([1.0_000, 0.5_426, 0.5_497, 0.2_200, 1.0_000, 1.0_000, 0.5_623, 1.0_000, 0.6_274]						)

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





    @skip_mps
    def        _lowerCamelCase			(						self					: Optional[int]						):





       '''simple docstring'''
       return super().test_save_load_local()





    @unittest.skip('''non-deterministic pipeline'''						)
    def        _lowerCamelCase			(						self					: Optional[Any]						):





       '''simple docstring'''
       return super().test_inference_batch_single_identical()





    @skip_mps
    def        _lowerCamelCase			(						self					: Dict						):





       '''simple docstring'''
       return super().test_dict_tuple_outputs_equivalent()





    @skip_mps
    def        _lowerCamelCase			(						self					: int						):





       '''simple docstring'''
       return super().test_save_load_optional_components()





    @skip_mps
    def        _lowerCamelCase			(						self					: Union[str, Any]						):





       '''simple docstring'''
       return super().test_attention_slicing_forward_pass()





@nightly
@require_torch_gpu
class 			lowerCAmelCase__(     unittest.TestCase    ):






    '''simple docstring'''





    def        _lowerCamelCase			(						self					: Tuple						):





       '''simple docstring'''
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





    def        _lowerCamelCase			(						self					: List[str]						):





       '''simple docstring'''
       UpperCAmelCase_				:   List[Any]							= load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/'''
           '''repaint/celeba_hq_256.png'''						)
       UpperCAmelCase_				:   int							= load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png'''						)
       UpperCAmelCase_				:   List[Any]							= load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/'''
           '''repaint/celeba_hq_256_result.npy'''						)

       UpperCAmelCase_				:   List[str]							= '''google/ddpm-ema-celebahq-256'''
       UpperCAmelCase_				:   Union[str, Any]							= UNetaDModel.from_pretrained(__snake_case						)
       UpperCAmelCase_				:   Dict							= RePaintScheduler.from_pretrained(__snake_case						)

       UpperCAmelCase_				:   Optional[int]							= RePaintPipeline(unet=__snake_case							, scheduler=__snake_case						).to(__snake_case						)
       repaint.set_progress_bar_config(disable=__snake_case						)
       repaint.enable_attention_slicing()

       UpperCAmelCase_				:   Optional[int]							= torch.manual_seed(0						)
       UpperCAmelCase_				:   List[str]							= repaint(
           __snake_case							, __snake_case							, num_inference_steps=250							, eta=0.0							, jump_length=10							, jump_n_sample=10							, generator=__snake_case							, output_type='''np'''							, )
       UpperCAmelCase_				:   Tuple							= output.images[0]

       assert image.shape == (256, 256, 3)
       assert np.abs(expected_image - image						).mean() < 1E-2