


'''simple docstring'''



import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
      import onnxruntime as ort



class      a    (		_a     ,  unittest.TestCase	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			str							       =       "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"

     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		int=0      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Optional[Any]  							=      floats_tensor((1, 3, 128, 128)							,			rng=random.Random(snake_case      )      )
          __UpperCAmelCase     :			List[str]  							=      np.random.RandomState(snake_case      )
          __UpperCAmelCase     :			Dict  							=      {
              '''prompt''': '''A painting of a squirrel eating a burger''',
              '''image''': image,
              '''generator''': generator,
              '''num_inference_steps''': 3,
              '''strength''': 0.75,
              '''guidance_scale''': 7.5,
              '''output_type''': '''numpy''',
          }
          return inputs

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Tuple:
          __UpperCAmelCase     :			Optional[int]  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,			provider='''CPUExecutionProvider'''      )
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			Optional[int]  							=      self.get_dummy_inputs()
          __UpperCAmelCase     :			List[str]  							=      pipe(**snake_case      ).images
          __UpperCAmelCase     :			Optional[Any]  							=      image[0, -3:, -3:, -1].flatten()

          assert image.shape == (1, 128, 128, 3)
          __UpperCAmelCase     :			Any  							=      np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087]      )
          assert np.abs(image_slice - expected_slice      ).max() < 1E-1

     def 			lowerCamelCase__			(    self					:		int      )						->							List[str]:
          __UpperCAmelCase     :			Any  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,			provider='''CPUExecutionProvider'''      )
          __UpperCAmelCase     :			Dict  							=      PNDMScheduler.from_config(pipe.scheduler.config							,			skip_prk_steps=snake_case      )
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			Tuple  							=      self.get_dummy_inputs()
          __UpperCAmelCase     :			int  							=      pipe(**snake_case      ).images
          __UpperCAmelCase     :			Optional[Any]  							=      image[0, -3:, -3:, -1]

          assert image.shape == (1, 128, 128, 3)
          __UpperCAmelCase     :			Tuple  							=      np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154]      )

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

     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Any:
          __UpperCAmelCase     :			Dict  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,			provider='''CPUExecutionProvider'''      )
          __UpperCAmelCase     :			Any  							=      LMSDiscreteScheduler.from_config(pipe.scheduler.config      )
          pipe.set_progress_bar_config(disable=snake_case      )

          # warmup pass to apply optimizations
          __UpperCAmelCase     :			Tuple  							=      pipe(**self.get_dummy_inputs()      )

          __UpperCAmelCase     :			Dict  							=      self.get_dummy_inputs()
          __UpperCAmelCase     :			str  							=      pipe(**snake_case      ).images
          __UpperCAmelCase     :			int  							=      image[0, -3:, -3:, -1]

          assert image.shape == (1, 128, 128, 3)
          __UpperCAmelCase     :			Tuple  							=      np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203]      )

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

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Optional[int]:
          __UpperCAmelCase     :			Optional[Any]  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,			provider='''CPUExecutionProvider'''      )
          __UpperCAmelCase     :			int  							=      EulerDiscreteScheduler.from_config(pipe.scheduler.config      )
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			Union[str, Any]  							=      self.get_dummy_inputs()
          __UpperCAmelCase     :			Dict  							=      pipe(**snake_case      ).images
          __UpperCAmelCase     :			List[Any]  							=      image[0, -3:, -3:, -1]

          assert image.shape == (1, 128, 128, 3)
          __UpperCAmelCase     :			Union[str, Any]  							=      np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304]      )

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

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							List[Any]:
          __UpperCAmelCase     :			List[Any]  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,			provider='''CPUExecutionProvider'''      )
          __UpperCAmelCase     :			List[Any]  							=      EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config      )
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			Optional[int]  							=      self.get_dummy_inputs()
          __UpperCAmelCase     :			Tuple  							=      pipe(**snake_case      ).images
          __UpperCAmelCase     :			Union[str, Any]  							=      image[0, -3:, -3:, -1]

          assert image.shape == (1, 128, 128, 3)
          __UpperCAmelCase     :			str  							=      np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304]      )

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






     def 			lowerCamelCase__			(    self					:		List[str]      )						->							Dict:
          __UpperCAmelCase     :			Optional[Any]  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,			provider='''CPUExecutionProvider'''      )
          __UpperCAmelCase     :			Dict  							=      DPMSolverMultistepScheduler.from_config(pipe.scheduler.config      )
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			Union[str, Any]  							=      self.get_dummy_inputs()
          __UpperCAmelCase     :			List[Any]  							=      pipe(**snake_case      ).images
          __UpperCAmelCase     :			List[str]  							=      image[0, -3:, -3:, -1]

          assert image.shape == (1, 128, 128, 3)
          __UpperCAmelCase     :			Union[str, Any]  							=      np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552]      )

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



@nightly
@require_onnxruntime
@require_torch_gpu
class      a    (		unittest.TestCase	):


     """simple docstring"""






     @property
     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Optional[Any]:
          return (
              "CUDAExecutionProvider",
              {
                  "gpu_mem_limit": "15000000000",  # 15GB
                  "arena_extend_strategy": "kSameAsRequested",
              },
          )

     @property
     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Tuple:
          __UpperCAmelCase     :			Any  							=      ort.SessionOptions()
          __UpperCAmelCase     :			List[Any]  							=      False
          return options

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							List[str]:
          __UpperCAmelCase     :			Optional[int]  							=      load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/img2img/sketch-mountains-input.jpg'''      )
          __UpperCAmelCase     :			List[Any]  							=      init_image.resize((768, 512)      )
          # using the PNDM scheduler by default
          __UpperCAmelCase     :			List[Any]  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(
              '''CompVis/stable-diffusion-v1-4'''							,			revision='''onnx'''							,			safety_checker=snake_case							,			feature_extractor=snake_case							,			provider=self.gpu_provider							,			sess_options=self.gpu_options							,			)
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			str  							=      '''A fantasy landscape, trending on artstation'''

          __UpperCAmelCase     :			Optional[Any]  							=      np.random.RandomState(0      )
          __UpperCAmelCase     :			Optional[int]  							=      pipe(
              prompt=snake_case							,			image=snake_case							,			strength=0.75							,			guidance_scale=7.5							,			num_inference_steps=10							,			generator=snake_case							,			output_type='''np'''							,			)
          __UpperCAmelCase     :			Optional[Any]  							=      output.images
          __UpperCAmelCase     :			List[Any]  							=      images[0, 255:258, 383:386, -1]

          assert images.shape == (1, 512, 768, 3)
          __UpperCAmelCase     :			Tuple  							=      np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019]      )
          # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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






     def 			lowerCamelCase__			(    self					:		List[str]      )						->							str:
          __UpperCAmelCase     :			Optional[int]  							=      load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/img2img/sketch-mountains-input.jpg'''      )
          __UpperCAmelCase     :			Dict  							=      init_image.resize((768, 512)      )
          __UpperCAmelCase     :			Any  							=      LMSDiscreteScheduler.from_pretrained(
              '''runwayml/stable-diffusion-v1-5'''							,			subfolder='''scheduler'''							,			revision='''onnx'''      )
          __UpperCAmelCase     :			Tuple  							=      OnnxStableDiffusionImgaImgPipeline.from_pretrained(
              '''runwayml/stable-diffusion-v1-5'''							,			revision='''onnx'''							,			scheduler=snake_case							,			safety_checker=snake_case							,			feature_extractor=snake_case							,			provider=self.gpu_provider							,			sess_options=self.gpu_options							,			)
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			List[str]  							=      '''A fantasy landscape, trending on artstation'''

          __UpperCAmelCase     :			Tuple  							=      np.random.RandomState(0      )
          __UpperCAmelCase     :			List[str]  							=      pipe(
              prompt=snake_case							,			image=snake_case							,			strength=0.75							,			guidance_scale=7.5							,			num_inference_steps=20							,			generator=snake_case							,			output_type='''np'''							,			)
          __UpperCAmelCase     :			Optional[int]  							=      output.images
          __UpperCAmelCase     :			List[Any]  							=      images[0, 255:258, 383:386, -1]

          assert images.shape == (1, 512, 768, 3)
          __UpperCAmelCase     :			Optional[Any]  							=      np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431]      )
          # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



'''simple docstring'''



# 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


__UpperCAmelCase      :Tuple			    =       "Create a default config file for Accelerate with only a few flags set."




def      _a     (						_lowercase :     List[Any]="no"      , _lowercase :     str = default_json_config_file      , _lowercase :     bool = False  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Dict  							=      Path(_lowercase  )
     path.parent.mkdir(parents=_lowercase      , exist_ok=_lowercase  )
     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
     __UpperCAmelCase     :			List[str]  							=      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}'  )
     __UpperCAmelCase     :			int  							=      {
         '''compute_environment''': '''LOCAL_MACHINE''',
         '''mixed_precision''': mixed_precision,
     }
     if torch.cuda.is_available():
          __UpperCAmelCase     :			Optional[Any]  							=      torch.cuda.device_count()
          __UpperCAmelCase     :			List[str]  							=      num_gpus
          __UpperCAmelCase     :			int  							=      False
          if num_gpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_GPU'''
          else:
               __UpperCAmelCase     :			int  							=      '''NO'''
     elif is_xpu_available() and use_xpu:
          __UpperCAmelCase     :			List[Any]  							=      torch.xpu.device_count()
          __UpperCAmelCase     :			List[Any]  							=      num_xpus
          __UpperCAmelCase     :			Optional[int]  							=      False
          if num_xpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_XPU'''
          else:
               __UpperCAmelCase     :			Optional[Any]  							=      '''NO'''
     elif is_npu_available():
          __UpperCAmelCase     :			Dict  							=      torch.npu.device_count()
          __UpperCAmelCase     :			Any  							=      num_npus
          __UpperCAmelCase     :			Any  							=      False
          if num_npus > 1:
               __UpperCAmelCase     :			Dict  							=      '''MULTI_NPU'''
          else:
               __UpperCAmelCase     :			Optional[int]  							=      '''NO'''
     else:
          __UpperCAmelCase     :			List[str]  							=      0
          __UpperCAmelCase     :			Dict  							=      True
          __UpperCAmelCase     :			Dict  							=      1
          __UpperCAmelCase     :			Tuple  							=      '''NO'''
     __UpperCAmelCase     :			List[Any]  							=      ClusterConfig(**_lowercase  )
     config.to_json_file(_lowercase  )
     return path




def      _a     (						_lowercase :     Union[str, Any]      , _lowercase :     str  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Optional[int]  							=      parser.add_parser('''default'''      , parents=_lowercase      , help=_lowercase      , formatter_class=_lowercase  )
     parser.add_argument(
         '''--config_file'''      , default=_lowercase      , 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=_lowercase      , 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=_lowercase  )
     return parser




def      _a     (						_lowercase :     List[Any]  ):





     '''simple docstring'''






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