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_ (	__A						,__A						,unittest.TestCase ):
   __A			:	int        =       UNetaDModel
   __A			:	List[str]        =       "sample"






   @property
   def    __UpperCamelCase  (   self       :  Dict						)      ->		Optional[Any]:
       lowercase__				:     List[str]					      =       4
       lowercase__				:     Optional[Any]					      =       14
       lowercase__				:     Any					      =       16

       lowercase__				:     Any					      =       floats_tensor((batch_size, num_features, seq_len)						).to(lowercase_						)
       lowercase__				:     int					      =       torch.tensor([10] * batch_size						).to(lowercase_						)

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






   @property
   def    __UpperCamelCase  (   self       :  List[Any]						)      ->		Tuple:
       return (4, 14, 16)






   @property
   def    __UpperCamelCase  (   self       :  Union[str, Any]						)      ->		Dict:
       return (4, 14, 16)






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






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






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






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






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






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






   @unittest.skipIf(torch_device == "mps"			,		"mish op not supported in MPS"						)
   def    __UpperCamelCase  (   self       :  Dict						)      ->		Tuple:
       super().test_model_from_pretrained()






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






   def    __UpperCamelCase  (   self       :  Any						)      ->		Any:
       lowercase__				:     List[str]					      =       {
           "block_out_channels": (32, 64, 1_28, 2_56),
           "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",
       }
       lowercase__				:     Tuple					      =       self.dummy_input
       return init_dict, inputs_dict






   @unittest.skipIf(torch_device == "mps"			,		"mish op not supported in MPS"						)
   def    __UpperCamelCase  (   self       :  Tuple						)      ->		Any:
       lowercase__      ,     lowercase__				:     Dict					      =       UNetaDModel.from_pretrained(
           "bglick13/hopper-medium-v2-value-function-hor32"			,		output_loading_info=lowercase_			,		subfolder="unet"						)
       self.assertIsNotNone(lowercase_						)
       self.assertEqual(len(loading_info["missing_keys"]						)			,		0						)

       model.to(lowercase_						)
       lowercase__				:     Optional[Any]					      =       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       :  Optional[Any]						)      ->		Tuple:
       lowercase__				:     Tuple					      =       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						)

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

       with torch.no_grad():
           lowercase__				:     str					      =       model(lowercase_			,		lowercase_						).sample.permute(0			,		2			,		1						)

       lowercase__				:     Optional[int]					      =       output[0, -3:, -3:].flatten()
       # fmt: off
       lowercase__				:     int					      =       torch.tensor([-2.13_71_72, 1.1_42_60_16, 0.3_68_86_87, -0.76_69_22, 0.7_30_31_46, 0.11_03_88_64, -0.4_76_06_33, 0.13_27_01_72, 0.02_59_13_48]						)
       # fmt: on
       self.assertTrue(torch.allclose(lowercase_			,		lowercase_			,		rtol=1E-3						)						)






   def    __UpperCamelCase  (   self       :  Union[str, Any]						)      ->		Union[str, Any]:
       # Not implemented yet for this UNet
       pass







   @slow
   def    __UpperCamelCase  (   self       :  int						)      ->		Tuple:
       lowercase__				:     List[str]					      =       "harmonai/maestro-150k"
       lowercase__				:     Dict					      =       UNetaDModel.from_pretrained(lowercase_			,		subfolder="unet"						)
       model.to(lowercase_						)

       lowercase__				:     List[str]					      =       6_55_36
       lowercase__				:     Optional[int]					      =       torch.sin(torch.arange(lowercase_						)[None, None, :].repeat(1			,		2			,		1						)						).to(lowercase_						)
       lowercase__				:     int					      =       torch.tensor([1]						).to(lowercase_						)

       with torch.no_grad():
           lowercase__				:     Optional[int]					      =       model(lowercase_			,		lowercase_						).sample

       lowercase__				:     Optional[Any]					      =       output.abs().sum()
       lowercase__				:     str					      =       output.abs().max()

       assert (output_sum - 2_24.08_96).abs() < 0.5
       assert (output_max - 0.06_07).abs() < 4E-4



class 						snake_case_ (	__A						,__A						,unittest.TestCase ):
   __A			:	Union[str, Any]        =       UNetaDModel
   __A			:	Any        =       "sample"






   @property
   def    __UpperCamelCase  (   self       :  Optional[int]						)      ->		Any:
       lowercase__				:     Dict					      =       4
       lowercase__				:     Any					      =       14
       lowercase__				:     Optional[Any]					      =       16

       lowercase__				:     Union[str, Any]					      =       floats_tensor((batch_size, num_features, seq_len)						).to(lowercase_						)
       lowercase__				:     Optional[int]					      =       torch.tensor([10] * batch_size						).to(lowercase_						)

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






   @property
   def    __UpperCamelCase  (   self       :  List[Any]						)      ->		Union[str, Any]:
       return (4, 14, 16)






   @property
   def    __UpperCamelCase  (   self       :  List[str]						)      ->		Tuple:
       return (4, 14, 1)






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






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






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






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






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






   @unittest.skipIf(torch_device == "mps"			,		"mish op not supported in MPS"						)
   def    __UpperCamelCase  (   self       :  Union[str, Any]						)      ->		Union[str, Any]:
       # UNetRL is a value-function is different output shape
       lowercase__      ,     lowercase__				:     List[Any]					      =       self.prepare_init_args_and_inputs_for_common()
       lowercase__				:     Optional[int]					      =       self.model_class(**lowercase_						)
       model.to(lowercase_						)
       model.eval()

       with torch.no_grad():
           lowercase__				:     int					      =       model(**lowercase_						)

           if isinstance(lowercase_			,		lowercase_						):
               lowercase__				:     Optional[Any]					      =       output.sample

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






   def    __UpperCamelCase  (   self       :  int						)      ->		Any:
       pass






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






   def    __UpperCamelCase  (   self       :  Dict						)      ->		List[str]:
       lowercase__				:     Optional[Any]					      =       {
           "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, 1_28, 2_56],
           "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",
       }
       lowercase__				:     List[str]					      =       self.dummy_input
       return init_dict, inputs_dict






   @unittest.skipIf(torch_device == "mps"			,		"mish op not supported in MPS"						)
   def    __UpperCamelCase  (   self       :  Dict						)      ->		Union[str, Any]:
       lowercase__      ,     lowercase__				:     Dict					      =       UNetaDModel.from_pretrained(
           "bglick13/hopper-medium-v2-value-function-hor32"			,		output_loading_info=lowercase_			,		subfolder="value_function"						)
       self.assertIsNotNone(lowercase_						)
       self.assertEqual(len(vf_loading_info["missing_keys"]						)			,		0						)

       value_function.to(lowercase_						)
       lowercase__				:     int					      =       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       :  int						)      ->		Any:
       lowercase__      ,     lowercase__				:     Tuple					      =       UNetaDModel.from_pretrained(
           "bglick13/hopper-medium-v2-value-function-hor32"			,		output_loading_info=lowercase_			,		subfolder="value_function"						)
       torch.manual_seed(0						)
       if torch.cuda.is_available():
           torch.cuda.manual_seed_all(0						)

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

       with torch.no_grad():
           lowercase__				:     Any					      =       value_function(lowercase_			,		lowercase_						).sample

       # fmt: off
       lowercase__				:     Tuple					      =       torch.tensor([1_65.25] * seq_len						)
       # fmt: on
       self.assertTrue(torch.allclose(lowercase_			,		lowercase_			,		rtol=1E-3						)						)







   def    __UpperCamelCase  (   self       :  Dict						)      ->		Optional[Any]:
       # Not implemented yet for this UNet
       pass




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCamelCase													=		{
    '''configuration_mobilenet_v1''': [
        '''MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''MobileNetV1Config''',
        '''MobileNetV1OnnxConfig''',
    ],
}

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCamelCase													=		['''MobileNetV1FeatureExtractor''']
      UpperCamelCase													=		['''MobileNetV1ImageProcessor''']

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      UpperCamelCase													=		[
          '''MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST''',
          '''MobileNetV1ForImageClassification''',
          '''MobileNetV1Model''',
          '''MobileNetV1PreTrainedModel''',
          '''load_tf_weights_in_mobilenet_v1''',
      ]


if TYPE_CHECKING:
      from .configuration_mobilenet_va import (
          MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP,
          MobileNetVaConfig,
          MobileNetVaOnnxConfig,
      )

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor
            from .image_processing_mobilenet_va import MobileNetVaImageProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_mobilenet_va import (
                MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST,
                MobileNetVaForImageClassification,
                MobileNetVaModel,
                MobileNetVaPreTrainedModel,
                load_tf_weights_in_mobilenet_va,
            )


else:
      import sys

      UpperCamelCase													=		_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



