





"""simple docstring"""
import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import 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
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class  _SCREAMING_SNAKE_CASE(       A   ,     A   ,     unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_       :				str     						=  StableDiffusionSAGPipeline
       SCREAMING_SNAKE_CASE_       :				List[str]     						=  TEXT_TO_IMAGE_PARAMS
       SCREAMING_SNAKE_CASE_       :				Optional[Any]     						=  TEXT_TO_IMAGE_BATCH_PARAMS
       SCREAMING_SNAKE_CASE_       :				List[Any]     						=  TEXT_TO_IMAGE_IMAGE_PARAMS
       SCREAMING_SNAKE_CASE_       :				List[Any]     						=  TEXT_TO_IMAGE_IMAGE_PARAMS
       SCREAMING_SNAKE_CASE_       :				str     						=  False




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





             """simple docstring"""






             torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  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		,)
             __SCREAMING_SNAKE_CASE       :Dict		    =  DDIMScheduler(
                 beta_start=0.0_0_0_8_5		,beta_end=0.0_1_2		,beta_schedule='''scaled_linear'''		,clip_sample=SCREAMING_SNAKE_CASE__		,set_alpha_to_one=SCREAMING_SNAKE_CASE__		,)
             torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  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		,)
             torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  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		,)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  CLIPTextModel(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Any		    =  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)

             __SCREAMING_SNAKE_CASE       :int		    =  {
                 '''unet''': unet,
                 '''scheduler''': scheduler,
                 '''vae''': vae,
                 '''text_encoder''': text_encoder,
                 '''tokenizer''': tokenizer,
                 '''safety_checker''': None,
                 '''feature_extractor''': None,
             }
             return components




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=0							)      ->				Dict:





             """simple docstring"""






             if str(SCREAMING_SNAKE_CASE__							).startswith('''mps'''							):
                   __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.manual_seed(SCREAMING_SNAKE_CASE__							)
             else:
                   __SCREAMING_SNAKE_CASE       :Optional[int]		    =  torch.Generator(device=SCREAMING_SNAKE_CASE__							).manual_seed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :int		    =  {
                 '''prompt''': '''.''',
                 '''generator''': generator,
                 '''num_inference_steps''': 2,
                 '''guidance_scale''': 1.0,
                 '''sag_scale''': 1.0,
                 '''output_type''': '''numpy''',
             }
             return inputs




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






             super().test_inference_batch_single_identical(expected_max_diff=3E-3							)






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




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






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




       def    _UpperCamelCase					(						self							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Tuple		    =  StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4'''							)
             __SCREAMING_SNAKE_CASE       :Tuple		    =  sag_pipe.to(SCREAMING_SNAKE_CASE__							)
             sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :Any		    =  '''.'''
             __SCREAMING_SNAKE_CASE       :Any		    =  torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  sag_pipe(
                 [prompt]		,generator=SCREAMING_SNAKE_CASE__		,guidance_scale=7.5		,sag_scale=1.0		,num_inference_steps=20		,output_type='''np'''							)

             __SCREAMING_SNAKE_CASE       :str		    =  output.images

             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  image[0, -3:, -3:, -1]

             assert image.shape == (1, 5_12, 5_12, 3)
             __SCREAMING_SNAKE_CASE       :int		    =  np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9]							)

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




       def    _UpperCamelCase					(						self							)      ->				int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Any		    =  StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  sag_pipe.to(SCREAMING_SNAKE_CASE__							)
             sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :int		    =  '''.'''
             __SCREAMING_SNAKE_CASE       :Any		    =  torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  sag_pipe(
                 [prompt]		,generator=SCREAMING_SNAKE_CASE__		,guidance_scale=7.5		,sag_scale=1.0		,num_inference_steps=20		,output_type='''np'''							)

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  output.images

             __SCREAMING_SNAKE_CASE       :List[str]		    =  image[0, -3:, -3:, -1]

             assert image.shape == (1, 5_12, 5_12, 3)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1]							)

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




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :int		    =  StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  sag_pipe.to(SCREAMING_SNAKE_CASE__							)
             sag_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  '''.'''
             __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  sag_pipe(
                 [prompt]		,width=7_68		,height=5_12		,generator=SCREAMING_SNAKE_CASE__		,guidance_scale=7.5		,sag_scale=1.0		,num_inference_steps=20		,output_type='''np'''		,)

             __SCREAMING_SNAKE_CASE       :List[str]		    =  output.images

             assert image.shape == (1, 5_12, 7_68, 3)






"""simple docstring"""
import baseaa
import io
import json
import os
from copy import deepcopy

from ..optimizer import AcceleratedOptimizer
from ..scheduler import AcceleratedScheduler






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__							)      ->				int:





             """simple docstring"""






             if isinstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							):
                   # Don't modify user's data should they want to reuse it (e.g. in tests), because once we
                   # modified it, it will not be accepted here again, since `auto` values would have been overridden
                   __SCREAMING_SNAKE_CASE       :Optional[int]		    =  deepcopy(SCREAMING_SNAKE_CASE__							)
             elif os.path.exists(SCREAMING_SNAKE_CASE__							):
                   with io.open(SCREAMING_SNAKE_CASE__		,'''r'''		,encoding='''utf-8'''							) as f:
                         __SCREAMING_SNAKE_CASE       :Dict		    =  json.load(SCREAMING_SNAKE_CASE__							)
             else:
                   try:
                         __SCREAMING_SNAKE_CASE       :str		    =  baseaa.urlsafe_baadecode(SCREAMING_SNAKE_CASE__							).decode('''utf-8'''							)
                         __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  json.loads(SCREAMING_SNAKE_CASE__							)
                   except (UnicodeDecodeError, AttributeError, ValueError):
                         raise ValueError(
                             f'''Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}'''							)

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  config

             self.set_stage_and_offload()




       def    _UpperCamelCase					(						self							)      ->				Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  self.get_value('''zero_optimization.stage'''		,-1							)

             # offload
             __SCREAMING_SNAKE_CASE       :Any		    =  False
             if self.is_zeroa() or self.is_zeroa():
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  set(['''cpu''', '''nvme''']							)
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  set(
                       [
                           self.get_value('''zero_optimization.offload_optimizer.device'''							),
                           self.get_value('''zero_optimization.offload_param.device'''							),
                       ]							)
                   if len(offload_devices & offload_devices_valid							) > 0:
                         __SCREAMING_SNAKE_CASE       :int		    =  True




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Any		    =  self.config

             # find the config node of interest if it exists
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  ds_key_long.split('''.'''							)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  nodes.pop()
             for node in nodes:
                   __SCREAMING_SNAKE_CASE       :Dict		    =  config.get(SCREAMING_SNAKE_CASE__							)
                   if config is None:
                         return None, ds_key

             return config, ds_key




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=None							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  self.find_config_node(SCREAMING_SNAKE_CASE__							)
             if config is None:
                   return default
             return config.get(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=False							)      ->				int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Dict		    =  self.config

             # find the config node of interest if it exists
             __SCREAMING_SNAKE_CASE       :str		    =  ds_key_long.split('''.'''							)
             for node in nodes:
                   __SCREAMING_SNAKE_CASE       :Any		    =  config
                   __SCREAMING_SNAKE_CASE       :int		    =  config.get(SCREAMING_SNAKE_CASE__							)
                   if config is None:
                         if must_exist:
                               raise ValueError(f'''Can\'t find {ds_key_long} entry in the config: {self.config}'''							)
                         else:
                               return

        # if found remove it
             if parent_config is not None:
                   parent_config.pop(SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__							)      ->				Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :int		    =  self.get_value(SCREAMING_SNAKE_CASE__							)
             return False if value is None else bool(SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__							)      ->				Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :str		    =  self.get_value(SCREAMING_SNAKE_CASE__							)
             return False if value is None else not bool(SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






             return self._stage == 2




       def    _UpperCamelCase					(						self							)      ->				List[Any]:





             """simple docstring"""






             return self._stage == 3




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





             """simple docstring"""






             return self._offload






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__							)      ->				Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  engine




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)      ->				List[Any]:





             """simple docstring"""






             self.engine.backward(SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)

             # Deepspeed's `engine.step` performs the following operations:
             # - gradient accumulation check
             # - gradient clipping
             # - optimizer step
             # - zero grad
             # - checking overflow
             # - lr_scheduler step (only if engine.lr_scheduler is not None)
             self.engine.step()
             # and this plugin overrides the above calls with no-ops when Accelerate runs under
             # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
             # training loop that works transparently under many training regimes.






class  _SCREAMING_SNAKE_CASE(       A  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__							)      ->				str:





             """simple docstring"""






             super().__init__(SCREAMING_SNAKE_CASE__		,device_placement=SCREAMING_SNAKE_CASE__		,scaler=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :int		    =  hasattr(self.optimizer		,'''overflow'''							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__=None							)      ->				Union[str, Any]:





             """simple docstring"""






             pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed




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





             """simple docstring"""






             pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed




       @property
       def    _UpperCamelCase					(						self							)      ->				Dict:





             """simple docstring"""






             if self.__has_overflow__:
                   return self.optimizer.overflow
             return False






class  _SCREAMING_SNAKE_CASE(       A  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Optional[int]:





             """simple docstring"""






             super().__init__(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self							)      ->				Optional[int]:





             """simple docstring"""






             pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=0.0_0_1		,SCREAMING_SNAKE_CASE__=0		,**SCREAMING_SNAKE_CASE__							)      ->				List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  params
             __SCREAMING_SNAKE_CASE       :str		    =  lr
             __SCREAMING_SNAKE_CASE       :str		    =  weight_decay
             __SCREAMING_SNAKE_CASE       :int		    =  kwargs






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=None		,SCREAMING_SNAKE_CASE__=0		,**SCREAMING_SNAKE_CASE__							)      ->				str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Dict		    =  optimizer
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  total_num_steps
             __SCREAMING_SNAKE_CASE       :Any		    =  warmup_num_steps
             __SCREAMING_SNAKE_CASE       :int		    =  kwargs