





'''simple docstring'''

import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
class        __lowerCAmelCase  (					__magic_name__				):






       """simple docstring"""
       _snake_case			:  Tuple		       =					['image_processor', 'tokenizer']
       _snake_case			:  Union[str, Any]		       =					'AutoImageProcessor'
       _snake_case			:  int		       =					'AutoTokenizer'





       def __init__(							self     :	Optional[int] ,				lowerCAmelCase__     :	int=None ,				lowerCAmelCase__     :	str=None ,				**lowerCAmelCase__     :	Tuple  )					->  Optional[int]:

            '''simple docstring'''




            _UpperCamelCase       					= None
            if "feature_extractor" in kwargs:
                 warnings.warn(
                     '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                     ''' instead.''' ,				lowerCAmelCase__ ,				)
                 _UpperCamelCase       					= kwargs.pop('''feature_extractor'''  )

            _UpperCamelCase       					= image_processor if image_processor is not None else feature_extractor
            if image_processor is None:
                 raise ValueError('''You need to specify an `image_processor`.'''  )
            if tokenizer is None:
                 raise ValueError('''You need to specify a `tokenizer`.'''  )

            super().__init__(lowerCAmelCase__ ,				lowerCAmelCase__  )
            _UpperCamelCase       					= self.image_processor
            _UpperCamelCase       					= False





       def __call__(							self     :	Any ,				*lowerCAmelCase__     :	Optional[Any] ,				**lowerCAmelCase__     :	Optional[int]  )					->  Optional[int]:

            '''simple docstring'''




            if self._in_target_context_manager:
                 return self.current_processor(*lowerCAmelCase__ ,				**lowerCAmelCase__  )

            _UpperCamelCase       					= kwargs.pop('''images''' ,				lowerCAmelCase__  )
            _UpperCamelCase       					= kwargs.pop('''text''' ,				lowerCAmelCase__  )
            if len(lowerCAmelCase__  ) > 0:
                 _UpperCamelCase       					= args[0]
                 _UpperCamelCase       					= args[1:]

            if images is None and text is None:
                 raise ValueError('''You need to specify either an `images` or `text` input to process.'''  )

            if images is not None:
                 _UpperCamelCase       					= self.image_processor(lowerCAmelCase__ ,				*lowerCAmelCase__ ,				**lowerCAmelCase__  )
            if text is not None:
                 _UpperCamelCase       					= self.tokenizer(lowerCAmelCase__ ,				**lowerCAmelCase__  )

            if text is None:
                 return inputs
            elif images is None:
                 return encodings
            else:
                 _UpperCamelCase       					= encodings['''input_ids''']
                 return inputs





       def snake_case__		(							self     :	Any ,				*lowerCAmelCase__     :	Optional[Any] ,				**lowerCAmelCase__     :	int  )					->  List[str]:

            '''simple docstring'''




            return self.tokenizer.batch_decode(*lowerCAmelCase__ ,				**lowerCAmelCase__  )





       def snake_case__		(							self     :	Any ,				*lowerCAmelCase__     :	Tuple ,				**lowerCAmelCase__     :	str  )					->  Dict:

            '''simple docstring'''




            return self.tokenizer.decode(*lowerCAmelCase__ ,				**lowerCAmelCase__  )





       @contextmanager
       def snake_case__		(							self     :	Optional[int]  )					->  Any:

            '''simple docstring'''




            warnings.warn(
                '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
                '''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
                '''your images inputs, or in a separate call.'''  )
            _UpperCamelCase       					= True
            _UpperCamelCase       					= self.tokenizer
            yield
            _UpperCamelCase       					= self.image_processor
            _UpperCamelCase       					= False





       @property
       def snake_case__		(							self     :	Optional[int]  )					->  Tuple:

            '''simple docstring'''




            warnings.warn(
                '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,				lowerCAmelCase__ ,				)
            return self.image_processor_class







       @property
       def snake_case__		(							self     :	Optional[int]  )					->  Tuple:

            '''simple docstring'''




            warnings.warn(
                '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' ,				lowerCAmelCase__ ,				)
            return self.image_processor










'''simple docstring'''

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__		:    Union[str, Any] =       logging.get_logger(__name__)







def       a__       (       lowercase      :  Dict,      lowercase      :  bool = True   )	->	int:





     """simple docstring"""

     _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=lowercase,      cross_attention_dim=lowercase   )
          _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        __lowerCAmelCase  (					__magic_name__		,		__magic_name__		,		unittest.TestCase				):






       """simple docstring"""
       _snake_case			:  int		       =					UNetaDConditionModel
       _snake_case			:  List[str]		       =					'sample'





       @property
       def snake_case__		(							self     :	Optional[int]  )					->  Any:

            '''simple docstring'''




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

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

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





       @property
       def snake_case__		(							self     :	Tuple  )					->  Optional[int]:

            '''simple docstring'''




            return (4, 4, 32, 32)





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

            '''simple docstring'''




            return (4, 4, 32, 32)





       def snake_case__		(							self     :	Optional[Any]  )					->  Tuple:

            '''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 snake_case__		(							self     :	Union[str, Any]  )					->  int:

            '''simple docstring'''




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

            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 snake_case__		(							self     :	Tuple  )					->  Tuple:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 32

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

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

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

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





       def snake_case__		(							self     :	str  )					->  Optional[Any]:

            '''simple docstring'''




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

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

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

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

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





       def snake_case__		(							self     :	Optional[Any]  )					->  str:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 8

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

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

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

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





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

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 8

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

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

            _UpperCamelCase       					= create_lora_layers(lowerCAmelCase__  )

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

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

            with torch.no_grad():
                 _UpperCamelCase       					= model(**lowerCAmelCase__ ,				cross_attention_kwargs={'''scale''': 0.0}  ).sample
                 _UpperCamelCase       					= model(**lowerCAmelCase__ ,				cross_attention_kwargs={'''scale''': 0.5}  ).sample
                 _UpperCamelCase       					= model(**lowerCAmelCase__ ,				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 snake_case__		(							self     :	str  )					->  Tuple:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 8

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

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

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

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

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

            with torch.no_grad():
                 _UpperCamelCase       					= new_model(**lowerCAmelCase__ ,				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 snake_case__		(							self     :	str  )					->  List[Any]:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 8

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

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

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

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

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

            with torch.no_grad():
                 _UpperCamelCase       					= new_model(**lowerCAmelCase__ ,				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 snake_case__		(							self     :	Tuple  )					->  List[Any]:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 8

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

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





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

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 8

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

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





       def snake_case__		(							self     :	Tuple  )					->  List[Any]:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 8

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

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

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

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

            model.set_attn_processor(AttnProcessor()  )

            with torch.no_grad():
                 _UpperCamelCase       					= model(**lowerCAmelCase__  ).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 snake_case__		(							self     :	List[str]  )					->  Tuple:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.prepare_init_args_and_inputs_for_common()

            _UpperCamelCase       					= 4

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

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

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

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

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







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

            '''simple docstring'''




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

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

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

            model.enable_forward_chunking()
            with torch.no_grad():
                 _UpperCamelCase       					= model(**lowerCAmelCase__  )[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.



