



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     __snake_case						(					UpperCamelCase_						,UpperCamelCase_						,unittest.TestCase						):
							_a      				=			UNetaDModel
							_a      				=			'''sample'''




							@property
							def        UpperCAmelCase__      (	self					:	List[Any]):
									lowerCAmelCase_      :					Optional[int]     =			4
									lowerCAmelCase_      :					Any     =			1_4
									lowerCAmelCase_      :					str     =			1_6

									lowerCAmelCase_      :					Tuple     =			floats_tensor((batch_size, num_features, seq_len)).to(A_)
									lowerCAmelCase_      :					Tuple     =			torch.tensor([1_0] * batch_size).to(A_)

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




							@property
							def        UpperCAmelCase__      (	self					:	Optional[Any]):
									return (4, 1_4, 1_6)




							@property
							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									return (4, 1_4, 1_6)




							def        UpperCAmelCase__      (	self					:	Any):
									pass




							def        UpperCAmelCase__      (	self					:	Optional[int]):
									pass




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Tuple):
									super().test_determinism()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	str):
									super().test_outputs_equivalence()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Any):
									super().test_from_save_pretrained()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	str):
									super().test_from_save_pretrained_variant()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Optional[Any]):
									super().test_model_from_pretrained()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	List[str]):
									super().test_output()




							def        UpperCAmelCase__      (	self					:	str):
									lowerCAmelCase_      :					Union[str, Any]     =			{
									    '''block_out_channels''': (3_2, 6_4, 1_2_8, 2_5_6),
									    '''in_channels''': 1_4,
									    '''out_channels''': 1_4,
									    '''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_      :					int     =			self.dummy_input
									return init_dict, inputs_dict




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Dict):
									lowerCAmelCase_      :					Tuple     =			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_      :					int     =			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        UpperCAmelCase__      (	self					:	Union[str, Any]):
									lowerCAmelCase_      :					int     =			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_      :					Optional[int]     =			model.config.in_channels
									lowerCAmelCase_      :					List[str]     =			1_6
									lowerCAmelCase_      :					Tuple     =			torch.randn((1, seq_len, num_features)).permute(
									    0    ,    2    ,    1)  # match original, we can update values and remove
									lowerCAmelCase_      :					List[Any]     =			torch.full((num_features,)    ,    0)

									with torch.no_grad():
											lowerCAmelCase_      :					Union[str, Any]     =			model(A_    ,    A_).sample.permute(0    ,    2    ,    1)

									lowerCAmelCase_      :					Union[str, Any]     =			output[0, -3:, -3:].flatten()
									# fmt: off
									lowerCAmelCase_      :					str     =			torch.tensor([-2.13_7172, 1.142_6016, 0.368_8687, -0.76_6922, 0.730_3146, 0.1103_8864, -0.476_0633, 0.1327_0172, 0.0259_1348])
									# fmt: on
									self.assertTrue(torch.allclose(A_    ,    A_    ,    rtol=1e-3))




							def        UpperCAmelCase__      (	self					:	Dict):
									# Not implemented yet for this UNet
									pass







							@slow
							def        UpperCAmelCase__      (	self					:	str):
									lowerCAmelCase_      :					Optional[int]     =			'''harmonai/maestro-150k'''
									lowerCAmelCase_      :					List[Any]     =			UNetaDModel.from_pretrained(A_    ,    subfolder='''unet''')
									model.to(A_)

									lowerCAmelCase_      :					Any     =			6_5_5_3_6
									lowerCAmelCase_      :					Dict     =			torch.sin(torch.arange(A_)[None, None, :].repeat(1    ,    2    ,    1)).to(A_)
									lowerCAmelCase_      :					List[str]     =			torch.tensor([1]).to(A_)

									with torch.no_grad():
											lowerCAmelCase_      :					List[Any]     =			model(A_    ,    A_).sample

									lowerCAmelCase_      :					str     =			output.abs().sum()
									lowerCAmelCase_      :					Any     =			output.abs().max()

									assert (output_sum - 224.0896).abs() < 0.5
									assert (output_max - 0.0607).abs() < 4e-4





class     __snake_case						(					UpperCamelCase_						,UpperCamelCase_						,unittest.TestCase						):
							_a      				=			UNetaDModel
							_a      				=			'''sample'''




							@property
							def        UpperCAmelCase__      (	self					:	Tuple):
									lowerCAmelCase_      :					int     =			4
									lowerCAmelCase_      :					List[Any]     =			1_4
									lowerCAmelCase_      :					List[str]     =			1_6

									lowerCAmelCase_      :					Optional[int]     =			floats_tensor((batch_size, num_features, seq_len)).to(A_)
									lowerCAmelCase_      :					Optional[Any]     =			torch.tensor([1_0] * batch_size).to(A_)

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




							@property
							def        UpperCAmelCase__      (	self					:	Optional[Any]):
									return (4, 1_4, 1_6)




							@property
							def        UpperCAmelCase__      (	self					:	Optional[int]):
									return (4, 1_4, 1)




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									super().test_determinism()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Optional[Any]):
									super().test_outputs_equivalence()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Tuple):
									super().test_from_save_pretrained()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									super().test_from_save_pretrained_variant()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	List[str]):
									super().test_model_from_pretrained()




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	List[Any]):
									# UNetRL is a value-function is different output shape
									lowerCAmelCase_      :					str     =			self.prepare_init_args_and_inputs_for_common()
									lowerCAmelCase_      :					Dict     =			self.model_class(**A_)
									model.to(A_)
									model.eval()

									with torch.no_grad():
											lowerCAmelCase_      :					Tuple     =			model(**A_)

											if isinstance(A_    ,    A_):
													lowerCAmelCase_      :					List[Any]     =			output.sample

									self.assertIsNotNone(A_)
									lowerCAmelCase_      :					Union[str, Any]     =			torch.Size((inputs_dict['''sample'''].shape[0], 1))
									self.assertEqual(output.shape    ,    A_    ,    '''Input and output shapes do not match''')




							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									pass




							def        UpperCAmelCase__      (	self					:	Optional[Any]):
									pass




							def        UpperCAmelCase__      (	self					:	Dict):
									lowerCAmelCase_      :					List[Any]     =			{
									    '''in_channels''': 1_4,
									    '''out_channels''': 1_4,
									    '''down_block_types''': ['''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D''', '''DownResnetBlock1D'''],
									    '''up_block_types''': [],
									    '''out_block_type''': '''ValueFunction''',
									    '''mid_block_type''': '''ValueFunctionMidBlock1D''',
									    '''block_out_channels''': [3_2, 6_4, 1_2_8, 2_5_6],
									    '''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_      :					Union[str, Any]     =			self.dummy_input
									return init_dict, inputs_dict




							@unittest.skipIf(torch_device == '''mps'''    ,    '''mish op not supported in MPS''')
							def        UpperCAmelCase__      (	self					:	int):
									lowerCAmelCase_      :					Tuple     =			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_      :					Any     =			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        UpperCAmelCase__      (	self					:	Tuple):
									lowerCAmelCase_      :					Union[str, Any]     =			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_      :					int     =			value_function.config.in_channels
									lowerCAmelCase_      :					Any     =			1_4
									lowerCAmelCase_      :					str     =			torch.randn((1, seq_len, num_features)).permute(
									    0    ,    2    ,    1)  # match original, we can update values and remove
									lowerCAmelCase_      :					Union[str, Any]     =			torch.full((num_features,)    ,    0)

									with torch.no_grad():
											lowerCAmelCase_      :					List[Any]     =			value_function(A_    ,    A_).sample

									# fmt: off
									lowerCAmelCase_      :					List[str]     =			torch.tensor([165.25] * seq_len)
									# fmt: on
									self.assertTrue(torch.allclose(A_    ,    A_    ,    rtol=1e-3))







							def        UpperCAmelCase__      (	self					:	List[str]):
									# Not implemented yet for this UNet
									pass









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_video_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import VideoMAEImageProcessor



class     __snake_case						(					unittest.TestCase						):




							def __init__(	self					:	str    ,    A_					:	str    ,    A_					:	int=7    ,    A_					:	List[Any]=3    ,    A_					:	Dict=1_0    ,    A_					:	List[str]=1_8    ,    A_					:	List[Any]=3_0    ,    A_					:	str=4_0_0    ,    A_					:	str=True    ,    A_					:	Tuple=None    ,    A_					:	Optional[Any]=True    ,    A_					:	Tuple=[0.5, 0.5, 0.5]    ,    A_					:	Any=[0.5, 0.5, 0.5]    ,    A_					:	List[str]=None    ,    ):
									lowerCAmelCase_      :					Optional[Any]     =			size if size is not None else {'''shortest_edge''': 1_8}
									lowerCAmelCase_      :					Optional[int]     =			crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8}

									lowerCAmelCase_      :					Any     =			parent
									lowerCAmelCase_      :					Optional[Any]     =			batch_size
									lowerCAmelCase_      :					List[Any]     =			num_channels
									lowerCAmelCase_      :					Optional[int]     =			num_frames
									lowerCAmelCase_      :					Optional[int]     =			image_size
									lowerCAmelCase_      :					List[Any]     =			min_resolution
									lowerCAmelCase_      :					str     =			max_resolution
									lowerCAmelCase_      :					List[str]     =			do_resize
									lowerCAmelCase_      :					int     =			size
									lowerCAmelCase_      :					Union[str, Any]     =			do_normalize
									lowerCAmelCase_      :					Union[str, Any]     =			image_mean
									lowerCAmelCase_      :					List[str]     =			image_std
									lowerCAmelCase_      :					Any     =			crop_size







							def        UpperCAmelCase__      (	self					:	Any):
									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "crop_size": self.crop_size,
									}





@require_torch
@require_vision
class     __snake_case						(					UpperCamelCase_						,unittest.TestCase						):
							_a      				=			VideoMAEImageProcessor if is_vision_available() else None




							def        UpperCAmelCase__      (	self					:	Tuple):
									lowerCAmelCase_      :					int     =			VideoMAEImageProcessingTester(self)




							@property
							def        UpperCAmelCase__      (	self					:	Tuple):
									return self.image_processor_tester.prepare_image_processor_dict()




							def        UpperCAmelCase__      (	self					:	Optional[int]):
									lowerCAmelCase_      :					int     =			self.image_processing_class(**self.image_processor_dict)
									self.assertTrue(hasattr(A_    ,    '''image_mean'''))
									self.assertTrue(hasattr(A_    ,    '''image_std'''))
									self.assertTrue(hasattr(A_    ,    '''do_normalize'''))
									self.assertTrue(hasattr(A_    ,    '''do_resize'''))
									self.assertTrue(hasattr(A_    ,    '''do_center_crop'''))
									self.assertTrue(hasattr(A_    ,    '''size'''))




							def        UpperCAmelCase__      (	self					:	Dict):
									lowerCAmelCase_      :					int     =			self.image_processing_class.from_dict(self.image_processor_dict)
									self.assertEqual(image_processor.size    ,    {'''shortest_edge''': 1_8})
									self.assertEqual(image_processor.crop_size    ,    {'''height''': 1_8, '''width''': 1_8})

									lowerCAmelCase_      :					str     =			self.image_processing_class.from_dict(self.image_processor_dict    ,    size=4_2    ,    crop_size=8_4)
									self.assertEqual(image_processor.size    ,    {'''shortest_edge''': 4_2})
									self.assertEqual(image_processor.crop_size    ,    {'''height''': 8_4, '''width''': 8_4})




							def        UpperCAmelCase__      (	self					:	Dict):
									pass




							def        UpperCAmelCase__      (	self					:	str):
									# Initialize image_processing
									lowerCAmelCase_      :					int     =			self.image_processing_class(**self.image_processor_dict)
									# create random PIL videos
									lowerCAmelCase_      :					Optional[int]     =			prepare_video_inputs(self.image_processor_tester    ,    equal_resolution=A_)
									for video in video_inputs:
											self.assertIsInstance(A_    ,    A_)
											self.assertIsInstance(video[0]    ,    Image.Image)

									# Test not batched input
									lowerCAmelCase_      :					int     =			image_processing(video_inputs[0]    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )

									# Test batched
									lowerCAmelCase_      :					Tuple     =			image_processing(A_    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )




							def        UpperCAmelCase__      (	self					:	int):
									# Initialize image_processing
									lowerCAmelCase_      :					Dict     =			self.image_processing_class(**self.image_processor_dict)
									# create random numpy tensors
									lowerCAmelCase_      :					str     =			prepare_video_inputs(self.image_processor_tester    ,    equal_resolution=A_    ,    numpify=A_)
									for video in video_inputs:
											self.assertIsInstance(A_    ,    A_)
											self.assertIsInstance(video[0]    ,    np.ndarray)

									# Test not batched input
									lowerCAmelCase_      :					Tuple     =			image_processing(video_inputs[0]    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )

									# Test batched
									lowerCAmelCase_      :					Union[str, Any]     =			image_processing(A_    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )







							def        UpperCAmelCase__      (	self					:	List[str]):
									# Initialize image_processing
									lowerCAmelCase_      :					Tuple     =			self.image_processing_class(**self.image_processor_dict)
									# create random PyTorch tensors
									lowerCAmelCase_      :					Tuple     =			prepare_video_inputs(self.image_processor_tester    ,    equal_resolution=A_    ,    torchify=A_)
									for video in video_inputs:
											self.assertIsInstance(A_    ,    A_)
											self.assertIsInstance(video[0]    ,    torch.Tensor)

									# Test not batched input
									lowerCAmelCase_      :					List[str]     =			image_processing(video_inputs[0]    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )

									# Test batched
									lowerCAmelCase_      :					List[Any]     =			image_processing(A_    ,    return_tensors='''pt''').pixel_values
									self.assertEqual(
									    encoded_videos.shape    ,    (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )    ,    )





