





import os
import tempfile
import unittest

import numpy as np
import torch

from diffusers.models import ModelMixin, UNetaDConditionModel
from diffusers.models.attention_processor import AttnProcessor, LoRAAttnProcessor
from diffusers.utils import (
    floats_tensor,
    logging,
    skip_mps,
    torch_device,
)
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

lowercase     :			List[Any]     						=	logging.get_logger(__name__)


def      SCREAMING_SNAKE_CASE      (   lowerCAmelCase     ,							lowerCAmelCase = True       ):
       _UpperCamelCase														=    {}
       for name in model.attn_processors.keys():
              _UpperCamelCase														=    name.endswith('''attn2.processor'''       ) and not (
                  name.startswith('''transformer_in'''       ) or '''temp_attentions''' in name.split('''.'''       )
              )
              _UpperCamelCase														=    model.config.cross_attention_dim if has_cross_attention else None
              if name.startswith('''mid_block'''       ):
                     _UpperCamelCase														=    model.config.block_out_channels[-1]
              elif name.startswith('''up_blocks'''       ):
                     _UpperCamelCase														=    int(name[len('''up_blocks.'''       )]       )
                     _UpperCamelCase														=    list(reversed(model.config.block_out_channels       )       )[block_id]
              elif name.startswith('''down_blocks'''       ):
                     _UpperCamelCase														=    int(name[len('''down_blocks.'''       )]       )
                     _UpperCamelCase														=    model.config.block_out_channels[block_id]
              elif name.startswith('''transformer_in'''       ):
                     # Note that the `8 * ...` comes from: https://github.com/huggingface/diffusers/blob/7139f0e874f10b2463caa8cbd585762a309d12d6/src/diffusers/models/unet_3d_condition.py#L148
                     _UpperCamelCase														=    8 * model.config.attention_head_dim

              _UpperCamelCase														=    LoRAAttnProcessor(hidden_size=lowerCAmelCase     ,							cross_attention_dim=lowerCAmelCase       )
              _UpperCamelCase														=    lora_attn_procs[name].to(model.device       )

              if mock_weights:
                     # add 1 to weights to mock trained weights
                     with torch.no_grad():
                            lora_attn_procs[name].to_q_lora.up.weight += 1
                            lora_attn_procs[name].to_k_lora.up.weight += 1
                            lora_attn_procs[name].to_v_lora.up.weight += 1
                            lora_attn_procs[name].to_out_lora.up.weight += 1

       return lora_attn_procs

@skip_mps
class 			__A(    __UpperCAmelCase    ,      __UpperCAmelCase    ,      unittest.TestCase			):
     __A							=							UNetaDConditionModel
     __A							=							"sample"

     @property
     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase														=    4
            _UpperCamelCase														=    4
            _UpperCamelCase														=    4
            _UpperCamelCase														=    (32, 32)

            _UpperCamelCase														=    floats_tensor((batch_size, num_channels, num_frames) + sizes   ).to(A   )
            _UpperCamelCase														=    torch.tensor([10]   ).to(A   )
            _UpperCamelCase														=    floats_tensor((batch_size, 4, 32)   ).to(A   )

            return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}

     @property
     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            return (4, 4, 32, 32)

     @property
     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            return (4, 4, 32, 32)

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase														=    {
                '''block_out_channels''': (32, 64),
                '''down_block_types''': (
                    '''CrossAttnDownBlock3D''',
                    '''DownBlock3D''',
                ),
                '''up_block_types''': ('''UpBlock3D''', '''CrossAttnUpBlock3D'''),
                '''cross_attention_dim''': 32,
                '''attention_head_dim''': 8,
                '''out_channels''': 4,
                '''in_channels''': 4,
                '''layers_per_block''': 1,
                '''sample_size''': 32,
            }
            _UpperCamelCase														=    self.dummy_input
            return init_dict, inputs_dict

     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available(),							reason='''XFormers attention is only available with CUDA and `xformers` installed''',							)
     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()
            _UpperCamelCase														=    self.model_class(**A   )

            model.enable_xformers_memory_efficient_attention()

            assert (
                model.mid_block.attentions[0].transformer_blocks[0].attna.processor.__class__.__name__
                == "XFormersAttnProcessor"
            ), "xformers is not enabled"

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    32

            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )
            model.eval()

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   )

                   if isinstance(A,							A   ):
                          _UpperCamelCase														=    output.sample

            self.assertIsNotNone(A   )
            _UpperCamelCase														=    inputs_dict['''sample'''].shape
            self.assertEqual(output.shape,							A,							'''Input and output shapes do not match'''   )

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()
            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )
            model.eval()

            with torch.no_grad():
                   # Warmup pass when using mps (see #372)
                   if torch_device == "mps" and isinstance(A,							A   ):
                          model(**self.dummy_input   )

                   _UpperCamelCase														=    model(**A   )
                   if isinstance(A,							A   ):
                          _UpperCamelCase														=    first.sample

                   _UpperCamelCase														=    model(**A   )
                   if isinstance(A,							A   ):
                          _UpperCamelCase														=    second.sample

            _UpperCamelCase														=    first.cpu().numpy()
            _UpperCamelCase														=    second.cpu().numpy()
            _UpperCamelCase														=    out_a[~np.isnan(A   )]
            _UpperCamelCase														=    out_a[~np.isnan(A   )]
            _UpperCamelCase														=    np.amax(np.abs(out_a - out_a   )   )
            self.assertLessEqual(A,							1E-5   )

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    8

            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )
            model.eval()

            model.set_attention_slice('''auto'''   )
            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   )
            assert output is not None

            model.set_attention_slice('''max'''   )
            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   )
            assert output is not None

            model.set_attention_slice(2   )
            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   )
            assert output is not None

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    8

            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   ).sample

            _UpperCamelCase														=    create_lora_layers(A   )

            # make sure we can set a list of attention processors
            model.set_attn_processor(A   )
            model.to(A   )

            # test that attn processors can be set to itself
            model.set_attn_processor(model.attn_processors   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A,							cross_attention_kwargs={'''scale''': 0.0}   ).sample
                   _UpperCamelCase														=    model(**A,							cross_attention_kwargs={'''scale''': 0.5}   ).sample
                   _UpperCamelCase														=    model(**A,							cross_attention_kwargs={'''scale''': 0.5}   ).sample

            assert (samplea - samplea).abs().max() < 3E-3
            assert (samplea - samplea).abs().max() < 3E-3

            # sample 2 and sample 3 should be different
            assert (samplea - samplea).abs().max() > 3E-3

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    8

            torch.manual_seed(0   )
            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   ).sample

            _UpperCamelCase														=    create_lora_layers(A   )
            model.set_attn_processor(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A,							cross_attention_kwargs={'''scale''': 0.5}   ).sample

            with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_attn_procs(A   )
                   self.assertTrue(os.path.isfile(os.path.join(A,							'''pytorch_lora_weights.bin'''   )   )   )
                   torch.manual_seed(0   )
                   _UpperCamelCase														=    self.model_class(**A   )
                   new_model.to(A   )
                   new_model.load_attn_procs(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    new_model(**A,							cross_attention_kwargs={'''scale''': 0.5}   ).sample

            assert (sample - new_sample).abs().max() < 1E-3

            # LoRA and no LoRA should NOT be the same
            assert (sample - old_sample).abs().max() > 1E-4

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    8

            torch.manual_seed(0   )
            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   ).sample

            _UpperCamelCase														=    create_lora_layers(A   )
            model.set_attn_processor(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A,							cross_attention_kwargs={'''scale''': 0.5}   ).sample

            with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_attn_procs(A,							safe_serialization=A   )
                   self.assertTrue(os.path.isfile(os.path.join(A,							'''pytorch_lora_weights.safetensors'''   )   )   )
                   torch.manual_seed(0   )
                   _UpperCamelCase														=    self.model_class(**A   )
                   new_model.to(A   )
                   new_model.load_attn_procs(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    new_model(**A,							cross_attention_kwargs={'''scale''': 0.5}   ).sample

            assert (sample - new_sample).abs().max() < 3E-3

            # LoRA and no LoRA should NOT be the same
            assert (sample - old_sample).abs().max() > 1E-4

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    8

            torch.manual_seed(0   )
            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )

            _UpperCamelCase														=    create_lora_layers(A,							mock_weights=A   )
            model.set_attn_processor(A   )
            # Saving as torch, properly reloads with directly filename
            with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_attn_procs(A   )
                   self.assertTrue(os.path.isfile(os.path.join(A,							'''pytorch_lora_weights.bin'''   )   )   )
                   torch.manual_seed(0   )
                   _UpperCamelCase														=    self.model_class(**A   )
                   new_model.to(A   )
                   new_model.load_attn_procs(A,							weight_name='''pytorch_lora_weights.bin'''   )

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    8

            torch.manual_seed(0   )
            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )

            _UpperCamelCase														=    create_lora_layers(A,							mock_weights=A   )
            model.set_attn_processor(A   )
            # Saving as torch, properly reloads with directly filename
            with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_attn_procs(A   )
                   self.assertTrue(os.path.isfile(os.path.join(A,							'''pytorch_lora_weights.bin'''   )   )   )
                   torch.manual_seed(0   )
                   _UpperCamelCase														=    self.model_class(**A   )
                   new_model.to(A   )
                   with self.assertRaises(A   ) as e:
                          new_model.load_attn_procs(A,							use_safetensors=A   )
                   self.assertIn('''Error no file named pytorch_lora_weights.safetensors''',							str(e.exception   )   )

     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    8

            torch.manual_seed(0   )
            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   ).sample

            _UpperCamelCase														=    create_lora_layers(A   )
            model.set_attn_processor(A   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A,							cross_attention_kwargs={'''scale''': 0.0}   ).sample

            model.set_attn_processor(AttnProcessor()   )

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   ).sample

            assert (sample - new_sample).abs().max() < 1E-4
            assert (sample - old_sample).abs().max() < 3E-3

     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available(),							reason='''XFormers attention is only available with CUDA and `xformers` installed''',							)
     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase														=    4

            torch.manual_seed(0   )
            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )
            _UpperCamelCase														=    create_lora_layers(A   )
            model.set_attn_processor(A   )

            # default
            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   ).sample

                   model.enable_xformers_memory_efficient_attention()
                   _UpperCamelCase														=    model(**A   ).sample

                   model.disable_xformers_memory_efficient_attention()
                   _UpperCamelCase														=    model(**A   ).sample

            assert (sample - on_sample).abs().max() < 1E-4
            assert (sample - off_sample).abs().max() < 1E-4



     def 						_UpperCamelCase  (   self   ):





            """simple docstring"""

            _UpperCamelCase							,		_UpperCamelCase														=    self.prepare_init_args_and_inputs_for_common()
            _UpperCamelCase														=    32

            _UpperCamelCase														=    self.model_class(**A   )
            model.to(A   )
            model.eval()

            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   )[0]

            model.enable_forward_chunking()
            with torch.no_grad():
                   _UpperCamelCase														=    model(**A   )[0]

            self.assertEqual(output.shape,							output_a.shape,							'''Shape doesn\'t match'''   )
            assert np.abs(output.cpu() - output_a.cpu()   ).max() < 1E-2


# (todo: sayakpaul) implement SLOW tests.













import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available


def      SCREAMING_SNAKE_CASE      (   lowerCAmelCase     ,							lowerCAmelCase     ,							lowerCAmelCase     ,							lowerCAmelCase=None       ):
       _UpperCamelCase														=    None
       # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
       if str(weight.dtype       ) == "torch.bfloat16":
              # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
              _UpperCamelCase														=    weight.view(torch.intaa       )
              _UpperCamelCase														=    '''bfloat16'''
       _UpperCamelCase														=    weight.cpu().numpy()
       _UpperCamelCase														=    os.path.join(lowerCAmelCase     ,							f'''{weight_name}.dat'''       )
       if index is not None:
              if dtype is None:
                     _UpperCamelCase														=    str(array.dtype       )
              _UpperCamelCase														=    {'''dtype''': dtype, '''shape''': list(array.shape       )}
       if array.ndim == 0:
              _UpperCamelCase														=    array[None]
       _UpperCamelCase														=    np.memmap(lowerCAmelCase     ,							dtype=array.dtype     ,							mode='''w+'''     ,							shape=array.shape       )
       _UpperCamelCase														=    array[:]
       file_array.flush()
       return index


def      SCREAMING_SNAKE_CASE      (   lowerCAmelCase     ,							lowerCAmelCase       ):
       _UpperCamelCase														=    tuple(weight_info['''shape''']       )
       if shape == ():
              # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
              _UpperCamelCase														=    (1,)

       _UpperCamelCase														=    weight_info['''dtype''']
       if dtype == "bfloat16":
              # NumPy does not support bfloat16 so this was saved as a int16
              _UpperCamelCase														=    '''int16'''

       _UpperCamelCase														=    np.memmap(lowerCAmelCase     ,							dtype=lowerCAmelCase     ,							shape=lowerCAmelCase     ,							mode='''r'''       )

       if len(weight_info['''shape''']       ) == 0:
              _UpperCamelCase														=    weight[0]
       _UpperCamelCase														=    torch.tensor(lowerCAmelCase       )
       if weight_info["dtype"] == "bfloat16":
              _UpperCamelCase														=    weight.view(torch.bfloataa       )

       return weight


def      SCREAMING_SNAKE_CASE      (   lowerCAmelCase     ,							lowerCAmelCase       ):
       if index is None or len(lowerCAmelCase       ) == 0:
              # Nothing to save
              return

       _UpperCamelCase														=    os.path.join(lowerCAmelCase     ,							'''index.json'''       )
       if os.path.isfile(lowerCAmelCase       ):
              with open(lowerCAmelCase     ,							'''r'''     ,							encoding='''utf-8'''       ) as f:
                     _UpperCamelCase														=    json.load(lowerCAmelCase       )
       else:
              _UpperCamelCase														=    {}
       current_index.update(lowerCAmelCase       )

       with open(lowerCAmelCase     ,							'''w'''     ,							encoding='''utf-8'''       ) as f:
              json.dump(lowerCAmelCase     ,							lowerCAmelCase     ,							indent=2       )


def      SCREAMING_SNAKE_CASE      (   lowerCAmelCase     ,							lowerCAmelCase       ):
       os.makedirs(lowerCAmelCase     ,							exist_ok=lowerCAmelCase       )
       _UpperCamelCase														=    {}
       for name, parameter in state_dict.items():
              _UpperCamelCase														=    offload_weight(lowerCAmelCase     ,							lowerCAmelCase     ,							lowerCAmelCase     ,							index=lowerCAmelCase       )

       # Update index
       save_offload_index(lowerCAmelCase     ,							lowerCAmelCase       )

class 			__A(    __UpperCAmelCase			):

     def __init__(   self,							A,							A   ):





            """simple docstring"""

            _UpperCamelCase														=    dataset
            _UpperCamelCase														=    prefix

     def __getitem__(   self,							A   ):





            """simple docstring"""

            return self.dataset[F'''{self.prefix}{key}''']

     def __iter__(   self   ):





            """simple docstring"""

            return iter([key for key in self.dataset if key.startswith(self.prefix   )]   )



     def __len__(   self   ):





            """simple docstring"""

            return len(self.dataset   )






class 			__A(    __UpperCAmelCase			):

     def __init__(   self,							A = None,							A = None,							A = None,							A=None,							):





            """simple docstring"""

            if state_dict is None and save_folder is None:
                   raise ValueError('''Need either a `state_dict` or a `save_folder` containing offloaded weights.'''   )

            _UpperCamelCase														=    {} if state_dict is None else state_dict
            _UpperCamelCase														=    save_folder
            if index is None and save_folder is not None:
                   with open(os.path.join(A,							'''index.json'''   )   ) as f:
                          _UpperCamelCase														=    json.load(A   )
            _UpperCamelCase														=    {} if index is None else index
            _UpperCamelCase														=    list(self.state_dict.keys()   )
            self.all_keys.extend([key for key in self.index if key not in self.all_keys]   )
            _UpperCamelCase														=    device

     def __getitem__(   self,							A   ):





            """simple docstring"""

            if key in self.state_dict:
                   return self.state_dict[key]
            _UpperCamelCase														=    self.index[key]
            if weight_info.get('''safetensors_file'''   ) is not None:
                   if not is_safetensors_available():
                          raise ImportError('''These offloaded weights require the use of safetensors: `pip install safetensors`.'''   )

                   from safetensors import safe_open

                   _UpperCamelCase														=    '''cpu''' if self.device is None else self.device
                   with safe_open(weight_info['''safetensors_file'''],							framework='''pt''',							device=A   ) as f:
                          _UpperCamelCase														=    f.get_tensor(weight_info.get('''weight_name''',							A   )   )

                   if "dtype" in weight_info:
                          return tensor.to(getattr(A,							weight_info['''dtype''']   )   )
                   else:
                          return tensor

            _UpperCamelCase														=    os.path.join(self.save_folder,							F'''{key}.dat'''   )
            return load_offloaded_weight(A,							A   )

     def __iter__(   self   ):





            """simple docstring"""

            return iter(self.all_keys   )



     def __len__(   self   ):





            """simple docstring"""

            return len(self.all_keys   )






def      SCREAMING_SNAKE_CASE      (   lowerCAmelCase     ,							lowerCAmelCase       ):
       _UpperCamelCase														=    {}
       for module_name in submodule_names:
              # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
              # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
              result.update(
                  {
                      key: param
                      for key, param in state_dict.items()
                      if key == module_name or key.startswith(module_name + '''.'''       )
                  }       )
       return result






