




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 		A__    (       lowercase_		,					lowercase_		,					unittest.TestCase			):
 lowerCamelCase__		:			int       =UNetaDModel
 lowerCamelCase__		:			str       ="sample"






 @property
 def 			lowercase				(     self						)				->       str:




      """simple docstring"""






      __magic_name__ :							str		       =							4
      __magic_name__ :							Optional[int]		       =							14
      __magic_name__ :							Optional[int]		       =							16

      __magic_name__ :							int		       =							floats_tensor((batch_size, num_features, seq_len)						).to(__UpperCamelCase						)
      __magic_name__ :							Tuple		       =							torch.tensor([10] * batch_size						).to(__UpperCamelCase						)

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






 @property
 def 			lowercase				(     self						)				->       int:




      """simple docstring"""






      return (4, 14, 16)






 @property
 def 			lowercase				(     self						)				->       int:




      """simple docstring"""






      return (4, 14, 16)






 def 			lowercase				(     self						)				->       Any:




      """simple docstring"""






      pass






 def 			lowercase				(     self						)				->       List[Any]:




      """simple docstring"""






      pass






 @unittest.skipIf(torch_device == '''mps'''    ,					'''mish op not supported in MPS'''						)
 def 			lowercase				(     self						)				->       Tuple:




      """simple docstring"""






      super().test_determinism()






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




      """simple docstring"""






      super().test_outputs_equivalence()






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




      """simple docstring"""






      super().test_from_save_pretrained()






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




      """simple docstring"""






      super().test_from_save_pretrained_variant()






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




      """simple docstring"""






      super().test_model_from_pretrained()






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




      """simple docstring"""






      super().test_output()






 def 			lowercase				(     self						)				->       Dict:




      """simple docstring"""






      __magic_name__ :							Optional[Any]		       =							{
          '''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''',
      }
      __magic_name__ :							Tuple		       =							self.dummy_input
      return init_dict, inputs_dict






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




      """simple docstring"""






      __magic_name__       ,			__magic_name__ :							List[Any]		       =							UNetaDModel.from_pretrained(
          '''bglick13/hopper-medium-v2-value-function-hor32'''    ,					output_loading_info=__UpperCamelCase    ,					subfolder='''unet'''						)
      self.assertIsNotNone(__UpperCamelCase						)
      self.assertEqual(len(loading_info['''missing_keys''']						)    ,					0						)

      model.to(__UpperCamelCase						)
      __magic_name__ :							Tuple		       =							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						)				->       List[str]:




      """simple docstring"""






      __magic_name__ :							str		       =							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						)

      __magic_name__ :							Optional[int]		       =							model.config.in_channels
      __magic_name__ :							str		       =							16
      __magic_name__ :							Optional[int]		       =							torch.randn((1, seq_len, num_features)						).permute(
          0    ,					2    ,					1						)  # match original, we can update values and remove
      __magic_name__ :							List[str]		       =							torch.full((num_features,)    ,					0						)

      with torch.no_grad():
           __magic_name__ :							Tuple		       =							model(__UpperCamelCase    ,					__UpperCamelCase						).sample.permute(0    ,					2    ,					1						)

      __magic_name__ :							Tuple		       =							output[0, -3:, -3:].flatten()
      # fmt: off
      __magic_name__ :							Optional[int]		       =							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(__UpperCamelCase    ,					__UpperCamelCase    ,					rtol=1e-3						)						)






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




      """simple docstring"""






      pass






 @slow
 def 			lowercase				(     self						)				->       int:




      """simple docstring"""






      __magic_name__ :							Tuple		       =							'''harmonai/maestro-150k'''
      __magic_name__ :							Optional[Any]		       =							UNetaDModel.from_pretrained(__UpperCamelCase    ,					subfolder='''unet'''						)
      model.to(__UpperCamelCase						)

      __magic_name__ :							Optional[Any]		       =							65536
      __magic_name__ :							Tuple		       =							torch.sin(torch.arange(__UpperCamelCase						)[None, None, :].repeat(1    ,					2    ,					1						)						).to(__UpperCamelCase						)
      __magic_name__ :							Optional[Any]		       =							torch.tensor([1]						).to(__UpperCamelCase						)

      with torch.no_grad():
           __magic_name__ :							Optional[Any]		       =							model(__UpperCamelCase    ,					__UpperCamelCase						).sample

      __magic_name__ :							str		       =							output.abs().sum()
      __magic_name__ :							List[Any]		       =							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 		A__    (       lowercase_		,					lowercase_		,					unittest.TestCase			):
 lowerCamelCase__		:			Any       =UNetaDModel
 lowerCamelCase__		:			Dict       ="sample"






 @property
 def 			lowercase				(     self						)				->       int:




      """simple docstring"""






      __magic_name__ :							int		       =							4
      __magic_name__ :							str		       =							14
      __magic_name__ :							str		       =							16

      __magic_name__ :							Dict		       =							floats_tensor((batch_size, num_features, seq_len)						).to(__UpperCamelCase						)
      __magic_name__ :							Any		       =							torch.tensor([10] * batch_size						).to(__UpperCamelCase						)

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






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




      """simple docstring"""






      return (4, 14, 16)






 @property
 def 			lowercase				(     self						)				->       int:




      """simple docstring"""






      return (4, 14, 1)






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




      """simple docstring"""






      super().test_determinism()






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




      """simple docstring"""






      super().test_outputs_equivalence()






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




      """simple docstring"""






      super().test_from_save_pretrained()






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




      """simple docstring"""






      super().test_from_save_pretrained_variant()






 @unittest.skipIf(torch_device == '''mps'''    ,					'''mish op not supported in MPS'''						)
 def 			lowercase				(     self						)				->       Tuple:




      """simple docstring"""






      super().test_model_from_pretrained()






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




      """simple docstring"""






      __magic_name__       ,			__magic_name__ :							Tuple		       =							self.prepare_init_args_and_inputs_for_common()
      __magic_name__ :							List[str]		       =							self.model_class(**__UpperCamelCase						)
      model.to(__UpperCamelCase						)
      model.eval()

      with torch.no_grad():
           __magic_name__ :							Union[str, Any]		       =							model(**__UpperCamelCase						)

           if isinstance(__UpperCamelCase    ,					__UpperCamelCase						):
                __magic_name__ :							Any		       =							output.sample

      self.assertIsNotNone(__UpperCamelCase						)
      __magic_name__ :							Dict		       =							torch.Size((inputs_dict['''sample'''].shape[0], 1)						)
      self.assertEqual(output.shape    ,					__UpperCamelCase    ,					'''Input and output shapes do not match'''						)






 def 			lowercase				(     self						)				->       Dict:




      """simple docstring"""






      pass






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




      """simple docstring"""






      pass






 def 			lowercase				(     self						)				->       List[Any]:




      """simple docstring"""






      __magic_name__ :							Dict		       =							{
          '''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''',
      }
      __magic_name__ :							Dict		       =							self.dummy_input
      return init_dict, inputs_dict






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




      """simple docstring"""






      __magic_name__       ,			__magic_name__ :							int		       =							UNetaDModel.from_pretrained(
          '''bglick13/hopper-medium-v2-value-function-hor32'''    ,					output_loading_info=__UpperCamelCase    ,					subfolder='''value_function'''						)
      self.assertIsNotNone(__UpperCamelCase						)
      self.assertEqual(len(vf_loading_info['''missing_keys''']						)    ,					0						)

      value_function.to(__UpperCamelCase						)
      __magic_name__ :							List[str]		       =							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						)				->       int:




      """simple docstring"""






      __magic_name__       ,			__magic_name__ :							int		       =							UNetaDModel.from_pretrained(
          '''bglick13/hopper-medium-v2-value-function-hor32'''    ,					output_loading_info=__UpperCamelCase    ,					subfolder='''value_function'''						)
      torch.manual_seed(0						)
      if torch.cuda.is_available():
           torch.cuda.manual_seed_all(0						)

      __magic_name__ :							Union[str, Any]		       =							value_function.config.in_channels
      __magic_name__ :							str		       =							14
      __magic_name__ :							Dict		       =							torch.randn((1, seq_len, num_features)						).permute(
          0    ,					2    ,					1						)  # match original, we can update values and remove
      __magic_name__ :							Optional[int]		       =							torch.full((num_features,)    ,					0						)

      with torch.no_grad():
           __magic_name__ :							Tuple		       =							value_function(__UpperCamelCase    ,					__UpperCamelCase						).sample

      # fmt: off
      __magic_name__ :							str		       =							torch.tensor([1_6_5.2_5] * seq_len						)
      # fmt: on
      self.assertTrue(torch.allclose(__UpperCamelCase    ,					__UpperCamelCase    ,					rtol=1e-3						)						)






 def 			lowercase				(     self						)				->       int:




      """simple docstring"""






      pass









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		,					__SCREAMING_SNAKE_CASE			):






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




						"""simple docstring"""






						__magic_name__ :							Tuple		       =							load_tool('''image-question-answering'''						)
						self.tool.setup()
						__magic_name__ :							Any		       =							load_tool('''image-question-answering'''    ,					remote=lowerCamelCase						)






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




						"""simple docstring"""






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






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




						"""simple docstring"""






						__magic_name__ :							Union[str, Any]		       =							Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''						)						) / '''000000039769.png'''						)
						__magic_name__ :							int		       =							self.remote_tool(lowerCamelCase    ,					'''How many cats are sleeping on the couch?'''						)
						self.assertEqual(lowerCamelCase    ,					'''2'''						)






	def 			lowercase				(     self						)				->       Any:




						"""simple docstring"""






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






	def 			lowercase				(     self						)				->       Dict:




						"""simple docstring"""






						__magic_name__ :							Optional[int]		       =							Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''						)						) / '''000000039769.png'''						)
						__magic_name__ :							Tuple		       =							self.remote_tool(image=lowerCamelCase    ,					question='''How many cats are sleeping on the couch?'''						)
						self.assertEqual(lowerCamelCase    ,					'''2'''						)



