




'''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()

_snake_case      :      int   							=		logging.get_logger(__name__)
def 		snake_case_    (UpperCamelCase       :  Tuple ,						UpperCamelCase       :  bool = True      ):





							'''simple docstring'''


							_a	     =				{}
							for name in model.attn_processors.keys():
														_a	     =				name.endswith('''attn2.processor'''      ) and not (
														    name.startswith('''transformer_in'''      ) or '''temp_attentions''' in name.split('''.'''      )
														)
														_a	     =				model.config.cross_attention_dim if has_cross_attention else None
														if name.startswith('''mid_block'''      ):
																					_a	     =				model.config.block_out_channels[-1]
														elif name.startswith('''up_blocks'''      ):
																					_a	     =				int(name[len('''up_blocks.'''      )]      )
																					_a	     =				list(reversed(model.config.block_out_channels      )      )[block_id]
														elif name.startswith('''down_blocks'''      ):
																					_a	     =				int(name[len('''down_blocks.'''      )]      )
																					_a	     =				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
																					_a	     =				8 * model.config.attention_head_dim

														_a	     =				LoRAAttnProcessor(hidden_size=UpperCamelCase ,						cross_attention_dim=UpperCamelCase      )
														_a	     =				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    (		_a     ,_a     ,unittest.TestCase    ):
							lowercase_							=				UNetaDConditionModel
							lowercase_							=				'sample'







							@property
							def    __lowerCAmelCase			(  self       :  Tuple					)			->							str:


														"""simple docstring"""


														_a	     =				4
														_a	     =				4
														_a	     =				4
														_a	     =				(32, 32)

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

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







							@property
							def    __lowerCAmelCase			(  self       :  List[Any]					)			->							List[str]:


														"""simple docstring"""


														return (4, 4, 32, 32)







							@property
							def    __lowerCAmelCase			(  self       :  int					)			->							str:


														"""simple docstring"""


														return (4, 4, 32, 32)







							def    __lowerCAmelCase			(  self       :  str					)			->							str:


														"""simple docstring"""


														_a	     =				{
														    '''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,
														}
														_a	     =				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    __lowerCAmelCase			(  self       :  List[str]					)			->							Optional[Any]:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()
														_a	     =				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    __lowerCAmelCase			(  self       :  List[str]					)			->							Dict:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				32

														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)
														model.eval()

														with torch.no_grad():
																					_a	     =				model(**lowerCAmelCase_					)

																					if isinstance(lowerCAmelCase_							,			lowerCAmelCase_					):
																												_a	     =				output.sample

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







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


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()
														_a	     =				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					)

																					_a	     =				model(**lowerCAmelCase_					)
																					if isinstance(lowerCAmelCase_							,			lowerCAmelCase_					):
																												_a	     =				first.sample

																					_a	     =				model(**lowerCAmelCase_					)
																					if isinstance(lowerCAmelCase_							,			lowerCAmelCase_					):
																												_a	     =				second.sample

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







							def    __lowerCAmelCase			(  self       :  int					)			->							Optional[Any]:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				8

														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)
														model.eval()

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

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

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







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


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				8

														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				model(**lowerCAmelCase_					).sample

														_a	     =				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():
																					_a	     =				model(**lowerCAmelCase_							,			cross_attention_kwargs={'''scale''': 0.0}					).sample
																					_a	     =				model(**lowerCAmelCase_							,			cross_attention_kwargs={'''scale''': 0.5}					).sample
																					_a	     =				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    __lowerCAmelCase			(  self       :  Optional[Any]					)			->							Optional[int]:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				8

														torch.manual_seed(0					)
														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				model(**lowerCAmelCase_					).sample

														_a	     =				create_lora_layers(lowerCAmelCase_					)
														model.set_attn_processor(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				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					)
																					_a	     =				self.model_class(**lowerCAmelCase_					)
																					new_model.to(lowerCAmelCase_					)
																					new_model.load_attn_procs(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				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    __lowerCAmelCase			(  self       :  int					)			->							int:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				8

														torch.manual_seed(0					)
														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				model(**lowerCAmelCase_					).sample

														_a	     =				create_lora_layers(lowerCAmelCase_					)
														model.set_attn_processor(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				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					)
																					_a	     =				self.model_class(**lowerCAmelCase_					)
																					new_model.to(lowerCAmelCase_					)
																					new_model.load_attn_procs(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				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    __lowerCAmelCase			(  self       :  List[str]					)			->							str:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				8

														torch.manual_seed(0					)
														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)

														_a	     =				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					)
																					_a	     =				self.model_class(**lowerCAmelCase_					)
																					new_model.to(lowerCAmelCase_					)
																					new_model.load_attn_procs(lowerCAmelCase_							,			weight_name='''pytorch_lora_weights.bin'''					)







							def    __lowerCAmelCase			(  self       :  int					)			->							List[str]:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				8

														torch.manual_seed(0					)
														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)

														_a	     =				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					)
																					_a	     =				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    __lowerCAmelCase			(  self       :  Union[str, Any]					)			->							Union[str, Any]:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				8

														torch.manual_seed(0					)
														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)

														with torch.no_grad():
																					_a	     =				model(**lowerCAmelCase_					).sample

														_a	     =				create_lora_layers(lowerCAmelCase_					)
														model.set_attn_processor(lowerCAmelCase_					)

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

														model.set_attn_processor(AttnProcessor()					)

														with torch.no_grad():
																					_a	     =				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    __lowerCAmelCase			(  self       :  Optional[Any]					)			->							str:


														"""simple docstring"""


														_a     ,							_a	     =				self.prepare_init_args_and_inputs_for_common()

														_a	     =				4

														torch.manual_seed(0					)
														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)
														_a	     =				create_lora_layers(lowerCAmelCase_					)
														model.set_attn_processor(lowerCAmelCase_					)

														# default
														with torch.no_grad():
																					_a	     =				model(**lowerCAmelCase_					).sample

																					model.enable_xformers_memory_efficient_attention()
																					_a	     =				model(**lowerCAmelCase_					).sample

																					model.disable_xformers_memory_efficient_attention()
																					_a	     =				model(**lowerCAmelCase_					).sample

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







							def    __lowerCAmelCase			(  self       :  Optional[Any]					)			->							List[Any]:


														"""simple docstring"""


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

														_a	     =				self.model_class(**lowerCAmelCase_					)
														model.to(lowerCAmelCase_					)
														model.eval()

														with torch.no_grad():
																					_a	     =				model(**lowerCAmelCase_					)[0]

														model.enable_forward_chunking()
														with torch.no_grad():
																					_a	     =				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.







'''simple docstring'''


import unittest
from pathlib import Path

from transformers import is_vision_available, load_tool
from transformers.testing_utils import get_tests_dir

from .test_tools_common import ToolTesterMixin


if is_vision_available():
				from PIL import Image

class 			A    (		unittest.TestCase     ,_a    ):







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


														"""simple docstring"""


														_a	     =				load_tool('''image-question-answering'''					)
														self.tool.setup()
														_a	     =				load_tool('''image-question-answering'''							,			remote=lowerCAmelCase_					)







							def    __lowerCAmelCase			(  self       :  Tuple					)			->							Optional[int]:


														"""simple docstring"""


														_a	     =				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''					)					) / '''000000039769.png'''					)
														_a	     =				self.tool(lowerCAmelCase_							,			'''How many cats are sleeping on the couch?'''					)
														self.assertEqual(lowerCAmelCase_							,			'''2'''					)







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


														"""simple docstring"""


														_a	     =				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''					)					) / '''000000039769.png'''					)
														_a	     =				self.remote_tool(lowerCAmelCase_							,			'''How many cats are sleeping on the couch?'''					)
														self.assertEqual(lowerCAmelCase_							,			'''2'''					)







							def    __lowerCAmelCase			(  self       :  Dict					)			->							Tuple:


														"""simple docstring"""


														_a	     =				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''					)					) / '''000000039769.png'''					)
														_a	     =				self.tool(image=lowerCAmelCase_							,			question='''How many cats are sleeping on the couch?'''					)
														self.assertEqual(lowerCAmelCase_							,			'''2'''					)







							def    __lowerCAmelCase			(  self       :  Tuple					)			->							Dict:


														"""simple docstring"""


														_a	     =				Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''					)					) / '''000000039769.png'''					)
														_a	     =				self.remote_tool(image=lowerCAmelCase_							,			question='''How many cats are sleeping on the couch?'''					)
														self.assertEqual(lowerCAmelCase_							,			'''2'''					)

