




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    PNDMScheduler,
    StableDiffusionLDMaDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS


enable_full_determinism()

class        lowercase      (    unittest.TestCase):
				__lowerCAmelCase    :    Optional[int]         =   StableDiffusionLDMaDPipeline
				__lowerCAmelCase    :    str         =   TEXT_TO_IMAGE_PARAMS
				__lowerCAmelCase    :    Tuple         =   TEXT_TO_IMAGE_BATCH_PARAMS
				__lowerCAmelCase    :    List[Any]         =   TEXT_TO_IMAGE_IMAGE_PARAMS







				def 					a_  (							self   :					List[str]       ):



					"""simple docstring"""

					torch.manual_seed(0       )
					A_  :				Optional[int]	   =		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      ,     )
					A_  :				int	   =		DDIMScheduler(
					    beta_start=0.00085      ,     beta_end=0.012      ,     beta_schedule='''scaled_linear'''      ,     clip_sample=_lowerCamelCase      ,     set_alpha_to_one=_lowerCamelCase      ,     )
					torch.manual_seed(0       )
					A_  :				List[str]	   =		AutoencoderKL(
					    block_out_channels=[32, 64]      ,     in_channels=6      ,     out_channels=6      ,     down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']      ,     up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']      ,     latent_channels=4      ,     )
					torch.manual_seed(0       )
					A_  :				List[Any]	   =		CLIPTextConfig(
					    bos_token_id=0      ,     eos_token_id=2      ,     hidden_size=32      ,     intermediate_size=37      ,     layer_norm_eps=1E-05      ,     num_attention_heads=4      ,     num_hidden_layers=5      ,     pad_token_id=1      ,     vocab_size=10_00      ,     )
					A_  :				Optional[Any]	   =		CLIPTextModel(_lowerCamelCase       )
					A_  :				str	   =		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

					A_  :				Union[str, Any]	   =		{
					    'unet': unet,
					    'scheduler': scheduler,
					    'vae': vae,
					    'text_encoder': text_encoder,
					    'tokenizer': tokenizer,
					    'safety_checker': None,
					    'feature_extractor': None,
					}
					return components







				def 					a_  (							self   :					Dict      ,     _lowerCamelCase   :					Union[str, Any]      ,     _lowerCamelCase   :					Dict=0       ):



					"""simple docstring"""

					if str(_lowerCamelCase       ).startswith('''mps'''       ):
						A_  :				List[Any]	   =		torch.manual_seed(_lowerCamelCase       )
					else:
						A_  :				int	   =		torch.Generator(device=_lowerCamelCase       ).manual_seed(_lowerCamelCase       )
					A_  :				str	   =		{
					    'prompt': 'A painting of a squirrel eating a burger',
					    'generator': generator,
					    'num_inference_steps': 2,
					    'guidance_scale': 6.0,
					    'output_type': 'numpy',
					}
					return inputs







				def 					a_  (							self   :					Tuple       ):



					"""simple docstring"""

					A_  :				str	   =		'cpu'  # ensure determinism for the device-dependent torch.Generator

					A_  :				Dict	   =		self.get_dummy_components()
					A_  :				Union[str, Any]	   =		StableDiffusionLDMaDPipeline(**_lowerCamelCase       )
					A_  :				str	   =		ldmad_pipe.to(_lowerCamelCase       )
					ldmad_pipe.set_progress_bar_config(disable=_lowerCamelCase       )

					A_  :				int	   =		self.get_dummy_inputs(_lowerCamelCase       )
					A_  :				List[str]	   =		ldmad_pipe(**_lowerCamelCase       )
					A_  :				List[Any]	   =		output.rgb, output.depth

					A_  :				int	   =		rgb[0, -3:, -3:, -1]
					A_  :				Dict	   =		depth[0, -3:, -1]

					assert rgb.shape == (1, 64, 64, 3)
					assert depth.shape == (1, 64, 64)

					A_  :				Any	   =		np.array(
					    [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262]       )
					A_  :				Dict	   =		np.array([103.46727, 85.812004, 87.849236]       )

					assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb       ).max() < 1E-2
					assert np.abs(image_slice_depth.flatten() - expected_slice_depth       ).max() < 1E-2







				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					A_  :				str	   =		self.get_dummy_components()
					A_  :				Any	   =		StableDiffusionLDMaDPipeline(**_lowerCamelCase       )
					A_  :				Optional[int]	   =		ldmad_pipe.to(_lowerCamelCase       )
					ldmad_pipe.set_progress_bar_config(disable=_lowerCamelCase       )

					A_  :				Optional[Any]	   =		self.get_dummy_inputs(_lowerCamelCase       )
					A_  :				Optional[int]	   =		3 * [inputs['prompt']]

					# forward
					A_  :				int	   =		ldmad_pipe(**_lowerCamelCase       )
					A_  :				List[str]	   =		output.rgb, output.depth
					A_  :				str	   =		rgb_slice_a[0, -3:, -3:, -1]
					A_  :				Union[str, Any]	   =		depth_slice_a[0, -3:, -1]

					A_  :				Union[str, Any]	   =		self.get_dummy_inputs(_lowerCamelCase       )
					A_  :				List[Any]	   =		3 * [inputs.pop('''prompt'''       )]

					A_  :				int	   =		ldmad_pipe.tokenizer(
					    _lowerCamelCase      ,     padding='''max_length'''      ,     max_length=ldmad_pipe.tokenizer.model_max_length      ,     truncation=_lowerCamelCase      ,     return_tensors='''pt'''      ,     )
					A_  :				int	   =		text_inputs['input_ids'].to(_lowerCamelCase       )

					A_  :				Optional[Any]	   =		ldmad_pipe.text_encoder(_lowerCamelCase       )[0]

					A_  :				int	   =		prompt_embeds

					# forward
					A_  :				str	   =		ldmad_pipe(**_lowerCamelCase       )
					A_  :				List[str]	   =		output.rgb, output.depth
					A_  :				Optional[int]	   =		rgb_slice_a[0, -3:, -3:, -1]
					A_  :				List[str]	   =		depth_slice_a[0, -3:, -1]

					assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten()       ).max() < 1E-4
					assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten()       ).max() < 1E-4







				def 					a_  (							self   :					Optional[int]       ):



					"""simple docstring"""

					A_  :				Optional[Any]	   =		'cpu'  # ensure determinism for the device-dependent torch.Generator
					A_  :				Optional[int]	   =		self.get_dummy_components()
					A_  :				Optional[Any]	   =		PNDMScheduler(skip_prk_steps=_lowerCamelCase       )
					A_  :				Union[str, Any]	   =		StableDiffusionLDMaDPipeline(**_lowerCamelCase       )
					A_  :				Optional[Any]	   =		ldmad_pipe.to(_lowerCamelCase       )
					ldmad_pipe.set_progress_bar_config(disable=_lowerCamelCase       )

					A_  :				Dict	   =		self.get_dummy_inputs(_lowerCamelCase       )
					A_  :				Any	   =		'french fries'
					A_  :				Optional[int]	   =		ldmad_pipe(**_lowerCamelCase      ,     negative_prompt=_lowerCamelCase       )

					A_  :				Any	   =		output.rgb, output.depth
					A_  :				str	   =		rgb[0, -3:, -3:, -1]
					A_  :				List[str]	   =		depth[0, -3:, -1]

					assert rgb.shape == (1, 64, 64, 3)
					assert depth.shape == (1, 64, 64)

					A_  :				List[str]	   =		np.array(
					    [0.37044, 0.71811503, 0.7223251, 0.48603675, 0.5638391, 0.6364948, 0.42833704, 0.4901315, 0.47926217]       )
					A_  :				str	   =		np.array([107.84738, 84.62802, 89.962135]       )
					assert np.abs(rgb_slice.flatten() - expected_slice_rgb       ).max() < 1E-2
					assert np.abs(depth_slice.flatten() - expected_slice_depth       ).max() < 1E-2

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







				def 					a_  (							self   :					str       ):



					"""simple docstring"""

					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()







				def 					a_  (							self   :					Optional[int]      ,     _lowerCamelCase   :					Optional[Any]      ,     _lowerCamelCase   :					int="cpu"      ,     _lowerCamelCase   :					Dict=torch.floataa      ,     _lowerCamelCase   :					Dict=0       ):



					"""simple docstring"""

					A_  :				int	   =		torch.Generator(device=_lowerCamelCase       ).manual_seed(_lowerCamelCase       )
					A_  :				Union[str, Any]	   =		np.random.RandomState(_lowerCamelCase       ).standard_normal((1, 4, 64, 64)       )
					A_  :				int	   =		torch.from_numpy(_lowerCamelCase       ).to(device=_lowerCamelCase      ,     dtype=_lowerCamelCase       )
					A_  :				Tuple	   =		{
					    'prompt': 'a photograph of an astronaut riding a horse',
					    'latents': latents,
					    'generator': generator,
					    'num_inference_steps': 3,
					    'guidance_scale': 7.5,
					    'output_type': 'numpy',
					}
					return inputs







				def 					a_  (							self   :					Dict       ):



					"""simple docstring"""

					A_  :				Optional[Any]	   =		StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d'''       )
					A_  :				List[Any]	   =		ldmad_pipe.to(_lowerCamelCase       )
					ldmad_pipe.set_progress_bar_config(disable=_lowerCamelCase       )

					A_  :				Tuple	   =		self.get_inputs(_lowerCamelCase       )
					A_  :				int	   =		ldmad_pipe(**_lowerCamelCase       )
					A_  :				Union[str, Any]	   =		output.rgb, output.depth
					A_  :				Dict	   =		rgb[0, -3:, -3:, -1].flatten()
					A_  :				int	   =		rgb[0, -3:, -1].flatten()

					assert rgb.shape == (1, 5_12, 5_12, 3)
					assert depth.shape == (1, 5_12, 5_12)

					A_  :				List[str]	   =		np.array(
					    [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706]       )
					A_  :				Any	   =		np.array(
					    [0.9263781, 0.6678672, 0.5486515, 0.92202145, 0.67831135, 0.56253487, 0.9241694, 0.7551478, 0.6459706]       )
					assert np.abs(rgb_slice - expected_slice_rgb       ).max() < 3E-3
					assert np.abs(depth_slice - expected_slice_depth       ).max() < 3E-3

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







				def 					a_  (							self   :					Optional[int]       ):



					"""simple docstring"""

					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()







				def 					a_  (							self   :					Any      ,     _lowerCamelCase   :					Tuple      ,     _lowerCamelCase   :					List[str]="cpu"      ,     _lowerCamelCase   :					Tuple=torch.floataa      ,     _lowerCamelCase   :					Optional[int]=0       ):



					"""simple docstring"""

					A_  :				str	   =		torch.Generator(device=_lowerCamelCase       ).manual_seed(_lowerCamelCase       )
					A_  :				Optional[Any]	   =		np.random.RandomState(_lowerCamelCase       ).standard_normal((1, 4, 64, 64)       )
					A_  :				Optional[int]	   =		torch.from_numpy(_lowerCamelCase       ).to(device=_lowerCamelCase      ,     dtype=_lowerCamelCase       )
					A_  :				Tuple	   =		{
					    'prompt': 'a photograph of an astronaut riding a horse',
					    'latents': latents,
					    'generator': generator,
					    'num_inference_steps': 50,
					    'guidance_scale': 7.5,
					    'output_type': 'numpy',
					}
					return inputs







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



					"""simple docstring"""

					A_  :				Optional[Any]	   =		StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d'''       ).to(_lowerCamelCase       )
					ldmad_pipe.set_progress_bar_config(disable=_lowerCamelCase       )

					A_  :				List[Any]	   =		self.get_inputs(_lowerCamelCase       )
					A_  :				int	   =		ldmad_pipe(**_lowerCamelCase       )
					A_  :				Any	   =		output.rgb, output.depth

					A_  :				str	   =		0.495586
					A_  :				List[Any]	   =		0.33795515
					A_  :				Optional[Any]	   =		112.48518
					A_  :				int	   =		98.489746
					assert np.abs(expected_rgb_mean - rgb.mean()       ) < 1E-3
					assert np.abs(expected_rgb_std - rgb.std()       ) < 1E-3
					assert np.abs(expected_depth_mean - depth.mean()       ) < 1E-3
					assert np.abs(expected_depth_std - depth.std()       ) < 1E-3







				def 					a_  (							self   :					List[Any]       ):



					"""simple docstring"""

					A_  :				Optional[Any]	   =		StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d-4c'''       ).to(_lowerCamelCase       )
					ldmad_pipe.set_progress_bar_config(disable=_lowerCamelCase       )

					A_  :				List[Any]	   =		self.get_inputs(_lowerCamelCase       )
					A_  :				int	   =		ldmad_pipe(**_lowerCamelCase       )
					A_  :				Tuple	   =		output.rgb, output.depth

					A_  :				List[str]	   =		0.4194127
					A_  :				int	   =		0.35375586
					A_  :				int	   =		0.5638502
					A_  :				Optional[Any]	   =		0.34686103

					assert rgb.shape == (1, 5_12, 5_12, 3)
					assert depth.shape == (1, 5_12, 5_12, 1)
					assert np.abs(expected_rgb_mean - rgb.mean()       ) < 1E-3
					assert np.abs(expected_rgb_std - rgb.std()       ) < 1E-3
					assert np.abs(expected_depth_mean - depth.mean()       ) < 1E-3
					assert np.abs(expected_depth_std - depth.std()       ) < 1E-3











"""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


_lowerCamelCase  :			List[Any]        =       'Create a default config file for Accelerate with only a few flags set.'

def 		lowercase_      (		_UpperCAmelCase="no"  ,      _UpperCAmelCase = default_json_config_file  ,      _UpperCAmelCase = False	):




	"""simple docstring"""






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

def 		lowercase_      (		_UpperCAmelCase  ,      _UpperCAmelCase	):




	"""simple docstring"""






	A_  :				Union[str, Any]	   =		parser.add_parser('''default'''  ,      parents=_UpperCAmelCase  ,      help=_UpperCAmelCase  ,      formatter_class=_UpperCAmelCase	)
	parser.add_argument(
	    '''--config_file'''  ,      default=_UpperCAmelCase  ,      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=_UpperCAmelCase  ,      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=_UpperCAmelCase	)
	return parser

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	A_  :				Dict	   =		write_basic_config(args.mixed_precision  ,      args.save_location	)
	if config_file:
		print(f"""accelerate configuration saved at {config_file}"""	)





