





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

import torch
from parameterized import parameterized

from diffusers import PriorTransformer
from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin


enable_full_determinism()






class  _SCREAMING_SNAKE_CASE(       A   ,     unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_       :				Union[str, Any]     						=  PriorTransformer
       SCREAMING_SNAKE_CASE_       :				Union[str, Any]     						=  '''hidden_states'''




       @property
       def    _UpperCamelCase					(						self							)      ->				Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  4
             __SCREAMING_SNAKE_CASE       :List[str]		    =  8
             __SCREAMING_SNAKE_CASE       :int		    =  7

             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  floats_tensor((batch_size, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :int		    =  floats_tensor((batch_size, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :str		    =  floats_tensor((batch_size, num_embeddings, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)

             return {
                 "hidden_states": hidden_states,
                 "timestep": 2,
                 "proj_embedding": proj_embedding,
                 "encoder_hidden_states": encoder_hidden_states,
             }




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





             """simple docstring"""






             torch.manual_seed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  4
             __SCREAMING_SNAKE_CASE       :Tuple		    =  8
             __SCREAMING_SNAKE_CASE       :str		    =  7

             __SCREAMING_SNAKE_CASE       :str		    =  torch.randn((batch_size, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  torch.randn((batch_size, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  torch.randn((batch_size, num_embeddings, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)

             return {
                 "hidden_states": hidden_states,
                 "timestep": 2,
                 "proj_embedding": proj_embedding,
                 "encoder_hidden_states": encoder_hidden_states,
             }




       @property
       def    _UpperCamelCase					(						self							)      ->				str:





             """simple docstring"""






             return (4, 8)




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





             """simple docstring"""






             return (4, 8)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Any		    =  {
                 '''num_attention_heads''': 2,
                 '''attention_head_dim''': 4,
                 '''num_layers''': 2,
                 '''embedding_dim''': 8,
                 '''num_embeddings''': 7,
                 '''additional_embeddings''': 4,
             }
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  self.dummy_input
             return init_dict, inputs_dict




       def    _UpperCamelCase					(						self							)      ->				int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE       :Optional[int]		    =  PriorTransformer.from_pretrained(
                 '''hf-internal-testing/prior-dummy'''		,output_loading_info=SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertEqual(len(loading_info['''missing_keys''']							)		,0							)

             model.to(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  model(**self.dummy_input							)[0]

             assert hidden_states is not None, "Make sure output is not None"




       def    _UpperCamelCase					(						self							)      ->				Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE       :Dict		    =  self.prepare_init_args_and_inputs_for_common()

             __SCREAMING_SNAKE_CASE       :List[str]		    =  self.model_class(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  inspect.signature(model.forward							)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  [*signature.parameters.keys()]

             __SCREAMING_SNAKE_CASE       :str		    =  ['''hidden_states''', '''timestep''']
             self.assertListEqual(arg_names[:2]		,SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Any		    =  PriorTransformer.from_pretrained('''hf-internal-testing/prior-dummy'''							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  model.to(SCREAMING_SNAKE_CASE__							)

             if hasattr(SCREAMING_SNAKE_CASE__		,'''set_default_attn_processor'''							):
                   model.set_default_attn_processor()

             __SCREAMING_SNAKE_CASE       :str		    =  self.get_dummy_seed_input()

             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE       :Tuple		    =  model(**SCREAMING_SNAKE_CASE__							)[0]

             __SCREAMING_SNAKE_CASE       :Dict		    =  output[0, :5].flatten().cpu()
             print(SCREAMING_SNAKE_CASE__							)

             # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
             # the expected output slices are not the same for CPU and GPU.
             __SCREAMING_SNAKE_CASE       :Any		    =  torch.tensor([-1.3_4_3_6, -0.2_8_7_0, 0.7_5_3_8, 0.4_3_6_8, -0.0_2_3_9]							)
             self.assertTrue(torch_all_close(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,rtol=1E-2							)							)






@slow
class  _SCREAMING_SNAKE_CASE(       unittest.TestCase  ):




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__=1		,SCREAMING_SNAKE_CASE__=7_68		,SCREAMING_SNAKE_CASE__=77		,SCREAMING_SNAKE_CASE__=0							)      ->				List[Any]:





             """simple docstring"""






             torch.manual_seed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  batch_size
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  embedding_dim
             __SCREAMING_SNAKE_CASE       :Tuple		    =  num_embeddings

             __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.randn((batch_size, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :int		    =  torch.randn((batch_size, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Any		    =  torch.randn((batch_size, num_embeddings, embedding_dim)							).to(SCREAMING_SNAKE_CASE__							)

             return {
                 "hidden_states": hidden_states,
                 "timestep": 2,
                 "proj_embedding": proj_embedding,
                 "encoder_hidden_states": encoder_hidden_states,
             }




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





             """simple docstring"""






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




       @parameterized.expand(
           [
               # fmt: off
               [13, [-0.5_8_6_1,  0.1_2_8_3, -0.0_9_3_1,  0.0_8_8_2,  0.4_4_7_6,  0.1_3_2_9, -0.0_4_9_8,  0.0_6_4_0]],
               [37, [-0.4_9_1_3,  0.0_1_1_0, -0.0_4_8_3,  0.0_5_4_1,  0.4_9_5_4, -0.0_1_7_0,  0.0_3_5_4,  0.1_6_5_1]],
               # fmt: on
           ]							)
       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[str]		    =  PriorTransformer.from_pretrained('''kandinsky-community/kandinsky-2-1-prior'''		,subfolder='''prior'''							)
             model.to(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  self.get_dummy_seed_input(seed=SCREAMING_SNAKE_CASE__							)

             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE       :Optional[int]		    =  model(**SCREAMING_SNAKE_CASE__							)[0]

             assert list(sample.shape							) == [1, 7_68]

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  sample[0, :8].flatten().cpu()
             print(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Tuple		    =  torch.tensor(SCREAMING_SNAKE_CASE__							)

             assert torch_all_close(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,atol=1E-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