



'''simple docstring'''







import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, slow, torch_device

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin

class      lowerCamelCase__     (     _A,     _A,     unittest.TestCase				):






	'''simple docstring'''

	A__		=	UNetaDModel
	A__		=	'''sample'''




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




								'''simple docstring'''





								lowerCAmelCase__  =   4
								lowerCAmelCase__  =   14
								lowerCAmelCase__  =   16

								lowerCAmelCase__  =   floats_tensor((batch_size, num_features, seq_len)					).to(__A					)
								lowerCAmelCase__  =   torch.tensor([10] * batch_size					).to(__A					)

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




	@property
	def      lowercase__							(  self		:  List[str]					)     ->			Optional[int]:




								'''simple docstring'''





								return (4, 14, 16)




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




								'''simple docstring'''





								return (4, 14, 16)




	def      lowercase__							(  self		:  str					)     ->			Dict:




								'''simple docstring'''





								pass




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




								'''simple docstring'''





								pass




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Any					)     ->			Optional[Any]:




								'''simple docstring'''





								super().test_determinism()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  int					)     ->			str:




								'''simple docstring'''





								super().test_outputs_equivalence()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  str					)     ->			Optional[int]:




								'''simple docstring'''





								super().test_from_save_pretrained()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  int					)     ->			Any:




								'''simple docstring'''





								super().test_from_save_pretrained_variant()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  str					)     ->			List[str]:




								'''simple docstring'''





								super().test_model_from_pretrained()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  List[Any]					)     ->			Optional[int]:




								'''simple docstring'''





								super().test_output()




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




								'''simple docstring'''





								lowerCAmelCase__  =   {
								    """block_out_channels""": (32, 64, 128, 256),
								    """in_channels""": 14,
								    """out_channels""": 14,
								    """time_embedding_type""": """positional""",
								    """use_timestep_embedding""": True,
								    """flip_sin_to_cos""": False,
								    """freq_shift""": 1.0,
								    """out_block_type""": """OutConv1DBlock""",
								    """mid_block_type""": """MidResTemporalBlock1D""",
								    """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""),
								    """up_block_types""": ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D"""),
								    """act_fn""": """mish""",
								}
								lowerCAmelCase__  =   self.dummy_input
								return init_dict, inputs_dict




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Optional[Any]					)     ->			str:




								'''simple docstring'''





								lowerCAmelCase__  ,lowerCAmelCase__  =   UNetaDModel.from_pretrained(
								    """bglick13/hopper-medium-v2-value-function-hor32"""   ,		output_loading_info=__A   ,		subfolder="""unet"""					)
								self.assertIsNotNone(__A					)
								self.assertEqual(len(loading_info["""missing_keys"""]					)   ,		0					)

								model.to(__A					)
								lowerCAmelCase__  =   model(**self.dummy_input					)

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




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Optional[int]					)     ->			List[str]:




								'''simple docstring'''





								lowerCAmelCase__  =   UNetaDModel.from_pretrained("""bglick13/hopper-medium-v2-value-function-hor32"""   ,		subfolder="""unet"""					)
								torch.manual_seed(0					)
								if torch.cuda.is_available():
															torch.cuda.manual_seed_all(0					)

								lowerCAmelCase__  =   model.config.in_channels
								lowerCAmelCase__  =   16
								lowerCAmelCase__  =   torch.randn((1, seq_len, num_features)					).permute(
								    0   ,		2   ,		1					)  # match original, we can update values and remove
								lowerCAmelCase__  =   torch.full((num_features,)   ,		0					)

								with torch.no_grad():
															lowerCAmelCase__  =   model(__A   ,		__A					).sample.permute(0   ,		2   ,		1					)

								lowerCAmelCase__  =   output[0, -3:, -3:].flatten()
								# fmt: off
								lowerCAmelCase__  =   torch.tensor([-2.1_3_7_1_7_2, 1.1_4_2_6_0_1_6, 0.3_6_8_8_6_8_7, -0.7_6_6_9_2_2, 0.7_3_0_3_1_4_6, 0.1_1_0_3_8_8_6_4, -0.4_7_6_0_6_3_3, 0.1_3_2_7_0_1_7_2, 0.0_2_5_9_1_3_4_8]					)
								# fmt: on
								self.assertTrue(torch.allclose(__A   ,		__A   ,		rtol=1E-3					)					)




	def      lowercase__							(  self		:  Any					)     ->			Any:




								'''simple docstring'''





								pass




	@slow
	def      lowercase__							(  self		:  Optional[int]					)     ->			List[Any]:




								'''simple docstring'''





								lowerCAmelCase__  =   """harmonai/maestro-150k"""
								lowerCAmelCase__  =   UNetaDModel.from_pretrained(__A   ,		subfolder="""unet"""					)
								model.to(__A					)

								lowerCAmelCase__  =   6_5536
								lowerCAmelCase__  =   torch.sin(torch.arange(__A					)[None, None, :].repeat(1   ,		2   ,		1					)					).to(__A					)
								lowerCAmelCase__  =   torch.tensor([1]					).to(__A					)

								with torch.no_grad():
															lowerCAmelCase__  =   model(__A   ,		__A					).sample

								lowerCAmelCase__  =   output.abs().sum()
								lowerCAmelCase__  =   output.abs().max()

								assert (output_sum - 2_2_4.0_8_9_6).abs() < 0.5
								assert (output_max - 0.0_6_0_7).abs() < 4E-4





class      lowerCamelCase__     (     _A,     _A,     unittest.TestCase				):






	'''simple docstring'''

	A__		=	UNetaDModel
	A__		=	'''sample'''




	@property
	def      lowercase__							(  self		:  str					)     ->			Any:




								'''simple docstring'''





								lowerCAmelCase__  =   4
								lowerCAmelCase__  =   14
								lowerCAmelCase__  =   16

								lowerCAmelCase__  =   floats_tensor((batch_size, num_features, seq_len)					).to(__A					)
								lowerCAmelCase__  =   torch.tensor([10] * batch_size					).to(__A					)

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




	@property
	def      lowercase__							(  self		:  Dict					)     ->			Tuple:




								'''simple docstring'''





								return (4, 14, 16)




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




								'''simple docstring'''





								return (4, 14, 1)




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  str					)     ->			List[Any]:




								'''simple docstring'''





								super().test_determinism()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Any					)     ->			int:




								'''simple docstring'''





								super().test_outputs_equivalence()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Tuple					)     ->			Optional[Any]:




								'''simple docstring'''





								super().test_from_save_pretrained()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Optional[int]					)     ->			Optional[int]:




								'''simple docstring'''





								super().test_from_save_pretrained_variant()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Any					)     ->			Dict:




								'''simple docstring'''





								super().test_model_from_pretrained()




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Union[str, Any]					)     ->			List[str]:




								'''simple docstring'''





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

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

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

								self.assertIsNotNone(__A					)
								lowerCAmelCase__  =   torch.Size((inputs_dict["""sample"""].shape[0], 1)					)
								self.assertEqual(output.shape   ,		__A   ,		"""Input and output shapes do not match"""					)




	def      lowercase__							(  self		:  Tuple					)     ->			Tuple:




								'''simple docstring'''





								pass




	def      lowercase__							(  self		:  Optional[int]					)     ->			Dict:




								'''simple docstring'''





								pass




	def      lowercase__							(  self		:  str					)     ->			int:




								'''simple docstring'''





								lowerCAmelCase__  =   {
								    """in_channels""": 14,
								    """out_channels""": 14,
								    """down_block_types""": ["""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""],
								    """up_block_types""": [],
								    """out_block_type""": """ValueFunction""",
								    """mid_block_type""": """ValueFunctionMidBlock1D""",
								    """block_out_channels""": [32, 64, 128, 256],
								    """layers_per_block""": 1,
								    """downsample_each_block""": True,
								    """use_timestep_embedding""": True,
								    """freq_shift""": 1.0,
								    """flip_sin_to_cos""": False,
								    """time_embedding_type""": """positional""",
								    """act_fn""": """mish""",
								}
								lowerCAmelCase__  =   self.dummy_input
								return init_dict, inputs_dict




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  str					)     ->			Any:




								'''simple docstring'''





								lowerCAmelCase__  ,lowerCAmelCase__  =   UNetaDModel.from_pretrained(
								    """bglick13/hopper-medium-v2-value-function-hor32"""   ,		output_loading_info=__A   ,		subfolder="""value_function"""					)
								self.assertIsNotNone(__A					)
								self.assertEqual(len(vf_loading_info["""missing_keys"""]					)   ,		0					)

								value_function.to(__A					)
								lowerCAmelCase__  =   value_function(**self.dummy_input					)

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




	@unittest.skipIf(torch_device == """mps"""   ,		"""mish op not supported in MPS"""					)
	def      lowercase__							(  self		:  Any					)     ->			Optional[Any]:




								'''simple docstring'''





								lowerCAmelCase__  ,lowerCAmelCase__  =   UNetaDModel.from_pretrained(
								    """bglick13/hopper-medium-v2-value-function-hor32"""   ,		output_loading_info=__A   ,		subfolder="""value_function"""					)
								torch.manual_seed(0					)
								if torch.cuda.is_available():
															torch.cuda.manual_seed_all(0					)

								lowerCAmelCase__  =   value_function.config.in_channels
								lowerCAmelCase__  =   14
								lowerCAmelCase__  =   torch.randn((1, seq_len, num_features)					).permute(
								    0   ,		2   ,		1					)  # match original, we can update values and remove
								lowerCAmelCase__  =   torch.full((num_features,)   ,		0					)

								with torch.no_grad():
															lowerCAmelCase__  =   value_function(__A   ,		__A					).sample

								# fmt: off
								lowerCAmelCase__  =   torch.tensor([1_6_5.2_5] * seq_len					)
								# fmt: on
								self.assertTrue(torch.allclose(__A   ,		__A   ,		rtol=1E-3					)					)




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




								'''simple docstring'''





								pass










'''simple docstring'''







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import DeiTImageProcessor

class      lowerCamelCase__     (     unittest.TestCase				):






	'''simple docstring'''

	def __init__(  self		:  List[str]   ,		__A		:  Any   ,		__A		:  Tuple=7   ,		__A		:  Dict=3   ,		__A		:  List[str]=18   ,		__A		:  Optional[int]=30   ,		__A		:  int=400   ,		__A		:  Union[str, Any]=True   ,		__A		:  Tuple=None   ,		__A		:  int=True   ,		__A		:  int=None   ,		__A		:  List[str]=True   ,		__A		:  Union[str, Any]=[0.5, 0.5, 0.5]   ,		__A		:  List[Any]=[0.5, 0.5, 0.5]   ,		)     ->			List[str]:




								'''simple docstring'''





								lowerCAmelCase__  =   size if size is not None else {"""height""": 20, """width""": 20}
								lowerCAmelCase__  =   crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

								lowerCAmelCase__  =   parent
								lowerCAmelCase__  =   batch_size
								lowerCAmelCase__  =   num_channels
								lowerCAmelCase__  =   image_size
								lowerCAmelCase__  =   min_resolution
								lowerCAmelCase__  =   max_resolution
								lowerCAmelCase__  =   do_resize
								lowerCAmelCase__  =   size
								lowerCAmelCase__  =   do_center_crop
								lowerCAmelCase__  =   crop_size
								lowerCAmelCase__  =   do_normalize
								lowerCAmelCase__  =   image_mean
								lowerCAmelCase__  =   image_std




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




								'''simple docstring'''





								return {
								    "do_resize": self.do_resize,
								    "size": self.size,
								    "do_center_crop": self.do_center_crop,
								    "crop_size": self.crop_size,
								    "do_normalize": self.do_normalize,
								    "image_mean": self.image_mean,
								    "image_std": self.image_std,
								}





@require_torch
@require_vision
class      lowerCamelCase__     (     _A,     unittest.TestCase				):






	'''simple docstring'''

	A__		=	DeiTImageProcessor if is_vision_available() else None
	A__		=	True




	def      lowercase__							(  self		:  List[Any]					)     ->			Dict:




								'''simple docstring'''





								lowerCAmelCase__  =   DeiTImageProcessingTester(self					)




	@property
	def      lowercase__							(  self		:  Any					)     ->			int:




								'''simple docstring'''





								return self.image_processor_tester.prepare_image_processor_dict()




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.image_processing_class(**self.image_processor_dict					)
								self.assertTrue(hasattr(__A   ,		"""do_resize"""					)					)
								self.assertTrue(hasattr(__A   ,		"""size"""					)					)
								self.assertTrue(hasattr(__A   ,		"""do_center_crop"""					)					)
								self.assertTrue(hasattr(__A   ,		"""center_crop"""					)					)
								self.assertTrue(hasattr(__A   ,		"""do_normalize"""					)					)
								self.assertTrue(hasattr(__A   ,		"""image_mean"""					)					)
								self.assertTrue(hasattr(__A   ,		"""image_std"""					)					)




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.image_processing_class.from_dict(self.image_processor_dict					)
								self.assertEqual(image_processor.size   ,		{"""height""": 20, """width""": 20}					)
								self.assertEqual(image_processor.crop_size   ,		{"""height""": 18, """width""": 18}					)

								lowerCAmelCase__  =   self.image_processing_class.from_dict(self.image_processor_dict   ,		size=42   ,		crop_size=84					)
								self.assertEqual(image_processor.size   ,		{"""height""": 42, """width""": 42}					)
								self.assertEqual(image_processor.crop_size   ,		{"""height""": 84, """width""": 84}					)




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




								'''simple docstring'''





								pass




	def      lowercase__							(  self		:  Dict					)     ->			Tuple:




								'''simple docstring'''





								lowerCAmelCase__  =   self.image_processing_class(**self.image_processor_dict					)
								# create random PIL images
								lowerCAmelCase__  =   prepare_image_inputs(self.image_processor_tester   ,		equal_resolution=__A					)
								for image in image_inputs:
															self.assertIsInstance(__A   ,		Image.Image					)

								# Test not batched input
								lowerCAmelCase__  =   image_processing(image_inputs[0]   ,		return_tensors="""pt"""					).pixel_values
								self.assertEqual(
								    encoded_images.shape   ,		(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size["""height"""],
								        self.image_processor_tester.crop_size["""width"""],
								    )   ,		)

								# Test batched
								lowerCAmelCase__  =   image_processing(__A   ,		return_tensors="""pt"""					).pixel_values
								self.assertEqual(
								    encoded_images.shape   ,		(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size["""height"""],
								        self.image_processor_tester.crop_size["""width"""],
								    )   ,		)




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




								'''simple docstring'''





								lowerCAmelCase__  =   self.image_processing_class(**self.image_processor_dict					)
								# create random numpy tensors
								lowerCAmelCase__  =   prepare_image_inputs(self.image_processor_tester   ,		equal_resolution=__A   ,		numpify=__A					)
								for image in image_inputs:
															self.assertIsInstance(__A   ,		np.ndarray					)

								# Test not batched input
								lowerCAmelCase__  =   image_processing(image_inputs[0]   ,		return_tensors="""pt"""					).pixel_values
								self.assertEqual(
								    encoded_images.shape   ,		(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size["""height"""],
								        self.image_processor_tester.crop_size["""width"""],
								    )   ,		)

								# Test batched
								lowerCAmelCase__  =   image_processing(__A   ,		return_tensors="""pt"""					).pixel_values
								self.assertEqual(
								    encoded_images.shape   ,		(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size["""height"""],
								        self.image_processor_tester.crop_size["""width"""],
								    )   ,		)




	def      lowercase__							(  self		:  List[str]					)     ->			Tuple:




								'''simple docstring'''





								lowerCAmelCase__  =   self.image_processing_class(**self.image_processor_dict					)
								# create random PyTorch tensors
								lowerCAmelCase__  =   prepare_image_inputs(self.image_processor_tester   ,		equal_resolution=__A   ,		torchify=__A					)
								for image in image_inputs:
															self.assertIsInstance(__A   ,		torch.Tensor					)

								# Test not batched input
								lowerCAmelCase__  =   image_processing(image_inputs[0]   ,		return_tensors="""pt"""					).pixel_values
								self.assertEqual(
								    encoded_images.shape   ,		(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size["""height"""],
								        self.image_processor_tester.crop_size["""width"""],
								    )   ,		)

								# Test batched
								lowerCAmelCase__  =   image_processing(__A   ,		return_tensors="""pt"""					).pixel_values
								self.assertEqual(
								    encoded_images.shape   ,		(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size["""height"""],
								        self.image_processor_tester.crop_size["""width"""],
								    )   ,		)





