

import random
import unittest

import torch

from diffusers import IFInpaintingSuperResolutionPipeline
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_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin





@skip_mps
class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			unittest.TestCase							):
  _a									=  IFInpaintingSuperResolutionPipeline
  _a									=  TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""width""", """height"""}
  _a									=  TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"""original_image"""}							)
  _a									=  PipelineTesterMixin.required_optional_params - {"""latents"""}




  def   A__     (				self					)  -> int:
        '''simple docstring'''






        return self._get_superresolution_dummy_components()




  def   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase=0					)  -> Optional[Any]:
        '''simple docstring'''






        if str(lowerCAmelCase					).startswith('mps'					):
              _lowercase	       =torch.manual_seed(lowerCAmelCase					)
        else:
              _lowercase	       =torch.Generator(device=lowerCAmelCase					).manual_seed(lowerCAmelCase					)

        _lowercase	       =floats_tensor((1, 3, 16, 16)							,   rng=random.Random(lowerCAmelCase					)					).to(lowerCAmelCase					)
        _lowercase	       =floats_tensor((1, 3, 32, 32)							,   rng=random.Random(lowerCAmelCase					)					).to(lowerCAmelCase					)
        _lowercase	       =floats_tensor((1, 3, 32, 32)							,   rng=random.Random(lowerCAmelCase					)					).to(lowerCAmelCase					)

        _lowercase	       ={
            'prompt': 'A painting of a squirrel eating a burger',
            'image': image,
            'original_image': original_image,
            'mask_image': mask_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   A__     (				self					)  -> Dict:
        '''simple docstring'''






        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3					)




  def   A__     (				self					)  -> Optional[Any]:
        '''simple docstring'''






        self._test_save_load_optional_components()




  @unittest.skipIf(torch_device != 'cuda'							,   reason='float16 requires CUDA'					)
  def   A__     (				self					)  -> Any:
        '''simple docstring'''






        super().test_save_load_floataa(expected_max_diff=1e-1					)




  def   A__     (				self					)  -> Any:
        '''simple docstring'''






        self._test_attention_slicing_forward_pass(expected_max_diff=1e-2					)




  def   A__     (				self					)  -> Tuple:
        '''simple docstring'''






        self._test_save_load_local()




  def   A__     (				self					)  -> str:
        '''simple docstring'''






        self._test_inference_batch_single_identical(
            expected_max_diff=1e-2							,   )





# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


lowercase_									=   'Create a default config file for Accelerate with only a few flags set.'
def      a      (			A__	:   Optional[Any]="no"      ,   A__	:   str = default_json_config_file      ,   A__	:   bool = False     )    ->      Optional[int]:





      """simple docstring"""



      _lowercase	       =Path(A__     )
      path.parent.mkdir(parents=A__      ,   exist_ok=A__     )
      if path.exists():
            print(
                F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''     )
            return False
      _lowercase	       =mixed_precision.lower()
      if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
            raise ValueError(
                F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''     )
      _lowercase	       ={
          'compute_environment': 'LOCAL_MACHINE',
          'mixed_precision': mixed_precision,
      }
      if torch.cuda.is_available():
            _lowercase	       =torch.cuda.device_count()
            _lowercase	       =num_gpus
            _lowercase	       =False
            if num_gpus > 1:
                  _lowercase	       ='MULTI_GPU'
            else:
                  _lowercase	       ='NO'
      elif is_xpu_available() and use_xpu:
            _lowercase	       =torch.xpu.device_count()
            _lowercase	       =num_xpus
            _lowercase	       =False
            if num_xpus > 1:
                  _lowercase	       ='MULTI_XPU'
            else:
                  _lowercase	       ='NO'
      elif is_npu_available():
            _lowercase	       =torch.npu.device_count()
            _lowercase	       =num_npus
            _lowercase	       =False
            if num_npus > 1:
                  _lowercase	       ='MULTI_NPU'
            else:
                  _lowercase	       ='NO'
      else:
            _lowercase	       =0
            _lowercase	       =True
            _lowercase	       =1
            _lowercase	       ='NO'
      _lowercase	       =ClusterConfig(**A__     )
      config.to_json_file(A__     )
      return path
def      a      (			A__	:   Dict      ,   A__	:   Optional[Any]     )    ->      List[Any]:





      """simple docstring"""



      _lowercase	       =parser.add_parser('default'      ,   parents=A__      ,   help=A__      ,   formatter_class=A__     )
      parser.add_argument(
          '--config_file'      ,   default=A__      ,   help=(
              'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
              'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
              'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
              'with \'huggingface\'.'
          )      ,   dest='save_location'      ,   )

      parser.add_argument(
          '--mixed_precision'      ,   choices=['no', 'fp16', 'bf16']      ,   type=A__      ,   help='Whether or not to use mixed precision training. '
          'Choose between FP16 and BF16 (bfloat16) training. '
          'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'      ,   default='no'      ,   )
      parser.set_defaults(func=A__     )
      return parser







def      a      (			A__	:   List[str]     )    ->      Any:





      """simple docstring"""



      _lowercase	       =write_basic_config(args.mixed_precision      ,   args.save_location     )
      if config_file:
            print(F'''accelerate configuration saved at {config_file}'''     )


