




"""simple docstring"""

import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


a     =      False





@skip_mps
class     lowercase_	(					__lowerCAmelCase      ,     __lowerCAmelCase      ,     __lowerCAmelCase      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					int				  =     StableDiffusionAttendAndExcitePipeline
 UpperCAmelCase   :					List[Any]				  =     False
 UpperCAmelCase   :					Dict				  =     TEXT_TO_IMAGE_PARAMS
 UpperCAmelCase   :					Tuple				  =     TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''}							)
 UpperCAmelCase   :					Tuple				  =     TEXT_TO_IMAGE_IMAGE_PARAMS
 UpperCAmelCase   :					Optional[int]				  =     TEXT_TO_IMAGE_IMAGE_PARAMS

 @classmethod
 def       lowerCAmelCase_							(			cls	:	Any		):
       super().setUpClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase		)

 @classmethod
 def       lowerCAmelCase_							(			cls	:	List[Any]		):
       super().tearDownClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       torch.manual_seed(0		)
       _A        =       UNetaDConditionModel(
           block_out_channels=(32, 64)   ,							layers_per_block=1   ,							sample_size=32   ,							in_channels=4   ,							out_channels=4   ,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')   ,							up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')   ,							cross_attention_dim=32   ,							attention_head_dim=(2, 4)   ,							use_linear_projection=_UpperCAmelCase   ,							)
       _A        =       DDIMScheduler(
           beta_start=0.0_0085   ,							beta_end=0.012   ,							beta_schedule='scaled_linear'   ,							clip_sample=_UpperCAmelCase   ,							set_alpha_to_one=_UpperCAmelCase   ,							)
       torch.manual_seed(0		)
       _A        =       AutoencoderKL(
           block_out_channels=[32, 64]   ,							in_channels=3   ,							out_channels=3   ,							down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']   ,							up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']   ,							latent_channels=4   ,							sample_size=128   ,							)
       torch.manual_seed(0		)
       _A        =       CLIPTextConfig(
           bos_token_id=0   ,							eos_token_id=2   ,							hidden_size=32   ,							intermediate_size=37   ,							layer_norm_eps=1E-0_5   ,							num_attention_heads=4   ,							num_hidden_layers=5   ,							pad_token_id=1   ,							vocab_size=1_000   ,							hidden_act='gelu'   ,							projection_dim=512   ,							)
       _A        =       CLIPTextModel(_UpperCAmelCase		)
       _A        =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

       _A        =       {
           'unet': unet,
           'scheduler': scheduler,
           'vae': vae,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'safety_checker': None,
           'feature_extractor': None,
       }

       return components

 def       lowerCAmelCase_							(			self	:	str   ,							_UpperCAmelCase	:	Dict   ,							_UpperCAmelCase	:	Optional[Any]=0		):
       if str(_UpperCAmelCase		).startswith('mps'		):
             _A        =       torch.manual_seed(_UpperCAmelCase		)
       else:
             _A        =       torch.Generator(device=_UpperCAmelCase		).manual_seed(_UpperCAmelCase		)
       _A        =       _A        =       {
           'prompt': 'a cat and a frog',
           'token_indices': [2, 5],
           'generator': generator,
           'num_inference_steps': 1,
           'guidance_scale': 6.0,
           'output_type': 'numpy',
           'max_iter_to_alter': 2,
           'thresholds': {0: 0.7},
       }
       return inputs

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       'cpu'

       _A        =       self.get_dummy_components()
       _A        =       self.pipeline_class(**_UpperCAmelCase		)
       pipe.to(_UpperCAmelCase		)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase		)

       _A        =       self.get_dummy_inputs(_UpperCAmelCase		)
       _A        =       pipe(**_UpperCAmelCase		).images
       _A        =       image[0, -3:, -3:, -1]

       self.assertEqual(image.shape   ,							(1, 64, 64, 3)		)
       _A        =       np.array(
           [0.6390_5364, 0.6289_7307, 0.4859_9017, 0.513_3624, 0.555_0048, 0.4576_9516, 0.5032_6973, 0.502_3139, 0.4538_4496]		)
       _A        =       np.abs(image_slice.flatten() - expected_slice		).max()
       self.assertLessEqual(_UpperCAmelCase   ,							1E-3		)

 def       lowerCAmelCase_							(			self	:	int		):
       super().test_cpu_offload_forward_pass(expected_max_diff=5E-4		)

 def       lowerCAmelCase_							(			self	:	Any		):
       # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
       self._test_inference_batch_consistent(batch_sizes=[1, 2]		)

 def       lowerCAmelCase_							(			self	:	Any		):
       self._test_inference_batch_single_identical(batch_size=2   ,							expected_max_diff=7E-4		)

 def       lowerCAmelCase_							(			self	:	List[str]		):
       super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3		)

 def       lowerCAmelCase_							(			self	:	Any		):
       super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4		)

 def       lowerCAmelCase_							(			self	:	Dict		):
       super().test_save_load_local(expected_max_difference=5E-4		)



 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       super().test_save_load_optional_components(expected_max_difference=4E-4		)





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



 '''simple docstring'''

 @classmethod
 def       lowerCAmelCase_							(			cls	:	int		):
       super().setUpClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase		)

 @classmethod
 def       lowerCAmelCase_							(			cls	:	List[str]		):
       super().tearDownClass()
       torch.use_deterministic_algorithms(_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()



 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       torch.manual_seed(51		)

       _A        =       StableDiffusionAttendAndExcitePipeline.from_pretrained(
           'CompVis/stable-diffusion-v1-4'   ,							safety_checker=_UpperCAmelCase   ,							torch_dtype=torch.floataa		)
       pipe.to('cuda'		)

       _A        =       'a painting of an elephant with glasses'
       _A        =       [5, 7]

       _A        =       pipe(
           prompt=_UpperCAmelCase   ,							token_indices=_UpperCAmelCase   ,							guidance_scale=7.5   ,							generator=_UpperCAmelCase   ,							num_inference_steps=5   ,							max_iter_to_alter=5   ,							output_type='numpy'   ,							).images[0]

       _A        =       load_numpy(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'		)
       assert np.abs((expected_image - image).max()		) < 5E-1







"""simple docstring"""

import inspect
import os
import unittest
from pathlib import Path

import torch

import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command





class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					str				  =     inspect.getfile(accelerate.test_utils							)
 UpperCAmelCase   :					Optional[Any]				  =     os.path.sep.join(mod_file.split(os.path.sep							)[:-1] + ['''scripts''', '''test_cli.py''']							)

 UpperCAmelCase   :					List[Any]				  =     ['''accelerate''', '''launch''']
 UpperCAmelCase   :					Dict				  =     Path.home() / '''.cache/huggingface/accelerate'''
 UpperCAmelCase   :					Union[str, Any]				  =     '''default_config.yaml'''
 UpperCAmelCase   :					Union[str, Any]				  =     config_folder / config_file
 UpperCAmelCase   :					Union[str, Any]				  =     config_folder / '''_default_config.yaml'''

 UpperCAmelCase   :					List[Any]				  =     Path('''tests/test_configs'''							)

 @classmethod
 def       lowerCAmelCase_							(			cls	:	List[Any]		):
       if cls.config_path.is_file():
             cls.config_path.rename(cls.changed_path		)

 @classmethod
 def       lowerCAmelCase_							(			cls	:	Tuple		):
       if cls.changed_path.is_file():
             cls.changed_path.rename(cls.config_path		)

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       self.base_cmd
       if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
             cmd += ["--multi_gpu"]
       execute_subprocess_async(cmd + [self.test_file_path]   ,							env=os.environ.copy()		)

 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       for config in sorted(self.test_config_path.glob('**/*.yaml'		)		):
             with self.subTest(config_file=_UpperCAmelCase		):
                   execute_subprocess_async(
                       self.base_cmd + ['--config_file', str(_UpperCAmelCase		), self.test_file_path]   ,							env=os.environ.copy()		)



 def       lowerCAmelCase_							(			self	:	Any		):
       execute_subprocess_async(['accelerate', 'test']   ,							env=os.environ.copy()		)





class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					Dict				  =     '''test-tpu'''
 UpperCAmelCase   :					Optional[int]				  =     '''us-central1-a'''
 UpperCAmelCase   :					List[str]				  =     '''ls'''
 UpperCAmelCase   :					str				  =     ['''accelerate''', '''tpu-config''']
 UpperCAmelCase   :					Optional[Any]				  =     '''cd /usr/share'''
 UpperCAmelCase   :					Optional[Any]				  =     '''tests/test_samples/test_command_file.sh'''
 UpperCAmelCase   :					str				  =     '''Running gcloud compute tpus tpu-vm ssh'''

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       run_command(
           self.cmd
           + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	Dict		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/0_12_0.yaml',
               '--command',
               self.command,
               '--tpu_zone',
               self.tpu_zone,
               '--tpu_name',
               self.tpu_name,
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       _A        =       run_command(
           self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug']   ,							return_stdout=_UpperCAmelCase		)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       run_command(
           self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	List[str]		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/latest.yaml',
               '--command',
               self.command,
               '--command',
               'echo "Hello World"',
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       run_command(
           self.cmd
           + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/0_12_0.yaml',
               '--command_file',
               self.command_file,
               '--tpu_zone',
               self.tpu_zone,
               '--tpu_name',
               self.tpu_name,
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	int		):
       _A        =       run_command(
           self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)



 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/latest.yaml',
               '--install_accelerate',
               '--accelerate_version',
               '12.0.0',
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

