
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			:       Dict      =						logging.get_logger(__name__)

def    __snake_case       (  __magic_name__		,						__magic_name__ = True	):







				'''simple docstring'''


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

								lowercase						    =			LoRAAttnProcessor(hidden_size=__magic_name__		,						cross_attention_dim=__magic_name__	)
								lowercase						    =			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      UpperCamelCase_			(			__a		,						__a		,						unittest.TestCase		):







						'''simple docstring'''



						UpperCamelCase			:     int							      =				UNetaDConditionModel
						UpperCamelCase			:     Tuple							      =				'''sample'''





						@property
						def 					SCREAMING_SNAKE_CASE( self       :Optional[int]    )     ->int:
										lowercase						    =			4
										lowercase						    =			4
										lowercase						    =			4
										lowercase						    =			(32, 32)

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

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





						@property
						def 					SCREAMING_SNAKE_CASE( self       :Any    )     ->str:
										return (4, 4, 32, 32)





						@property
						def 					SCREAMING_SNAKE_CASE( self       :Optional[int]    )     ->Tuple:
										return (4, 4, 32, 32)





						def 					SCREAMING_SNAKE_CASE( self       :Tuple    )     ->Optional[int]:
										lowercase						    =			{
										    "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,
										}
										lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :List[str]    )     ->Dict:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()
										lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :List[Any]    )     ->Tuple:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			32

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

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

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

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





						def 					SCREAMING_SNAKE_CASE( self       :int    )     ->Union[str, Any]:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()
										lowercase						    =			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    )

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

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

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





						def 					SCREAMING_SNAKE_CASE( self       :List[str]    )     ->Tuple:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			8

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

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

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

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





						def 					SCREAMING_SNAKE_CASE( self       :List[str]    )     ->Union[str, Any]:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			8

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

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

										lowercase						    =			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():
														lowercase						    =			model(**lowerCAmelCase__		,						cross_attention_kwargs={"scale": 0.0}    ).sample
														lowercase						    =			model(**lowerCAmelCase__		,						cross_attention_kwargs={"scale": 0.5}    ).sample
														lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :int    )     ->Optional[int]:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			8

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

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

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

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

										with torch.no_grad():
														lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :Tuple    )     ->Any:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			8

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

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

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

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

										with torch.no_grad():
														lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :List[Any]    )     ->List[str]:
										# enable deterministic behavior for gradient checkpointing
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			8

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

										lowercase						    =			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    )
														lowercase						    =			self.model_class(**lowerCAmelCase__    )
														new_model.to(lowerCAmelCase__    )
														new_model.load_attn_procs(lowerCAmelCase__		,						weight_name="pytorch_lora_weights.bin"    )





						def 					SCREAMING_SNAKE_CASE( self       :List[Any]    )     ->Any:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			8

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

										lowercase						    =			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    )
														lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :Tuple    )     ->Optional[Any]:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			8

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

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

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

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

										model.set_attn_processor(AttnProcessor()    )

										with torch.no_grad():
														lowercase						    =			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 					SCREAMING_SNAKE_CASE( self       :str    )     ->List[str]:
										# enable deterministic behavior for gradient checkpointing
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()

										lowercase						    =			4

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

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

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

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

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





						def 					SCREAMING_SNAKE_CASE( self       :List[Any]    )     ->Optional[Any]:
										lowercase    ,  lowercase						    =			self.prepare_init_args_and_inputs_for_common()
										lowercase						    =			32

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

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

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


from ...configuration_utils import PretrainedConfig
from ...utils import logging


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

_snake_case			:       Dict      =						{
    "google/reformer-crime-and-punishment": (
        "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/config.json"
    ),
    "google/reformer-enwik8": "https://huggingface.co/google/reformer-enwik8/resolve/main/config.json",
}





class      UpperCamelCase_			(			__a		):







						'''simple docstring'''



						UpperCamelCase			:     Any							      =				'''reformer'''
						UpperCamelCase			:     List[str]							      =				['''past_buckets_states''']
						UpperCamelCase			:     Optional[int]							      =				{}





						def __init__( self       :Dict		,						lowerCAmelCase__       :Any=64		,						lowerCAmelCase__       :str=["local", "lsh", "local", "lsh", "local", "lsh"]		,						lowerCAmelCase__       :Optional[Any]=1.0		,						lowerCAmelCase__       :List[str]=True		,						lowerCAmelCase__       :Optional[Any]=[64, 64]		,						lowerCAmelCase__       :Tuple=[64, 192]		,						lowerCAmelCase__       :Union[str, Any]=0		,						lowerCAmelCase__       :Optional[Any]=2		,						lowerCAmelCase__       :List[str]=512		,						lowerCAmelCase__       :Any=None		,						lowerCAmelCase__       :int="relu"		,						lowerCAmelCase__       :Tuple=0.05		,						lowerCAmelCase__       :int=256		,						lowerCAmelCase__       :Optional[Any]=0.02		,						lowerCAmelCase__       :Optional[int]=False		,						lowerCAmelCase__       :Optional[Any]=1E-1_2		,						lowerCAmelCase__       :int=1		,						lowerCAmelCase__       :Optional[Any]=0		,						lowerCAmelCase__       :Any=0.05		,						lowerCAmelCase__       :Optional[int]=64		,						lowerCAmelCase__       :List[Any]=64		,						lowerCAmelCase__       :Tuple=0.0		,						lowerCAmelCase__       :Tuple=1		,						lowerCAmelCase__       :List[str]=0		,						lowerCAmelCase__       :Dict=4096		,						lowerCAmelCase__       :Tuple=12		,						lowerCAmelCase__       :Tuple=None		,						lowerCAmelCase__       :Union[str, Any]=1		,						lowerCAmelCase__       :int=0		,						lowerCAmelCase__       :Optional[Any]=320		,						lowerCAmelCase__       :Optional[Any]=False		,						lowerCAmelCase__       :Optional[int]=True		,						lowerCAmelCase__       :str=None		,						**lowerCAmelCase__       :Any		,						)     ->Any:
										lowercase						    =			hash_seed
										lowercase						    =			vocab_size
										lowercase						    =			attention_head_size
										lowercase						    =			hidden_size
										lowercase						    =			num_attention_heads
										lowercase						    =			num_hashes
										lowercase						    =			len(lowerCAmelCase__    )
										lowercase						    =			tuple(lowerCAmelCase__    ) if isinstance(lowerCAmelCase__		,						lowerCAmelCase__    ) else num_buckets
										lowercase						    =			lsh_attn_chunk_length
										lowercase						    =			local_attn_chunk_length
										lowercase						    =			lsh_num_chunks_after
										lowercase						    =			lsh_num_chunks_before
										lowercase						    =			local_num_chunks_after
										lowercase						    =			local_num_chunks_before
										lowercase						    =			hidden_act
										lowercase						    =			feed_forward_size
										lowercase						    =			hidden_dropout_prob
										lowercase						    =			lsh_attention_probs_dropout_prob
										lowercase						    =			local_attention_probs_dropout_prob
										lowercase						    =			max_position_embeddings
										lowercase						    =			initializer_range
										lowercase						    =			layer_norm_eps
										lowercase						    =			axial_pos_embds
										lowercase						    =			tuple(lowerCAmelCase__    )
										lowercase						    =			tuple(lowerCAmelCase__    )
										lowercase						    =			axial_norm_std
										lowercase						    =			chunk_size_lm_head
										lowercase						    =			attn_layers
										lowercase						    =			use_cache
										lowercase						    =			classifier_dropout
										super().__init__(
										    pad_token_id=lowerCAmelCase__		,						eos_token_id=lowerCAmelCase__		,						is_decoder=lowerCAmelCase__		,						tie_word_embeddings=lowerCAmelCase__		,						**lowerCAmelCase__		,						)
