






'''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        a__     (      lowerCamelCase			,    lowerCamelCase			,    unittest.TestCase    ):
     '''simple docstring'''







     _snake_case							   =	UNetaDModel
     _snake_case							   =	'sample'






     @property
     def      _UpperCamelCase (self     :						Optional[Any]       )	->							List[str]:
           __A		 =   4
           __A		 =   14
           __A		 =   16

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

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






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






     @property
     def      _UpperCamelCase (self     :						Optional[int]       )	->							List[Any]:
           return (4, 14, 16)






     def      _UpperCamelCase (self     :						List[Any]       )	->							List[str]:
           pass






     def      _UpperCamelCase (self     :						Any       )	->							Tuple:
           pass






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






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






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






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






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






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






     def      _UpperCamelCase (self     :						Any       )	->							Union[str, Any]:
           __A		 =   {
               "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",
           }
           __A		 =   self.dummy_input
           return init_dict, inputs_dict






     @unittest.skipIf(torch_device == "mps"					,					"mish op not supported in MPS"       )
     def      _UpperCamelCase (self     :						Union[str, Any]       )	->							Union[str, Any]:
           __A ,					__A		 =   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__       )
           __A		 =   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     :						Dict       )	->							Optional[int]:
           __A		 =   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       )

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

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

           __A		 =   output[0, -3:, -3:].flatten()
           # fmt: off
           __A		 =   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     :						str       )	->							Tuple:
           # Not implemented yet for this UNet
           pass






     @slow
     def      _UpperCamelCase (self     :						Union[str, Any]       )	->							str:
           __A		 =   "harmonai/maestro-150k"
           __A		 =   UNetaDModel.from_pretrained(lowercase__					,					subfolder="unet"       )
           model.to(lowercase__       )

           __A		 =   65536
           __A		 =   torch.sin(torch.arange(lowercase__       )[None, None, :].repeat(1					,					2					,					1       )       ).to(lowercase__       )
           __A		 =   torch.tensor([1]       ).to(lowercase__       )

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

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

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







class        a__     (      lowerCamelCase			,    lowerCamelCase			,    unittest.TestCase    ):
     '''simple docstring'''







     _snake_case							   =	UNetaDModel
     _snake_case							   =	'sample'






     @property
     def      _UpperCamelCase (self     :						int       )	->							Optional[Any]:
           __A		 =   4
           __A		 =   14
           __A		 =   16

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

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






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






     @property
     def      _UpperCamelCase (self     :						Dict       )	->							Tuple:
           return (4, 14, 1)






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






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






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






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






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






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

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

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

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






     def      _UpperCamelCase (self     :						Any       )	->							List[Any]:
           pass






     def      _UpperCamelCase (self     :						Dict       )	->							str:
           pass






     def      _UpperCamelCase (self     :						str       )	->							Optional[Any]:
           __A		 =   {
               "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",
           }
           __A		 =   self.dummy_input
           return init_dict, inputs_dict






     @unittest.skipIf(torch_device == "mps"					,					"mish op not supported in MPS"       )
     def      _UpperCamelCase (self     :						Union[str, Any]       )	->							List[str]:
           __A ,					__A		 =   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__       )
           __A		 =   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     :						Optional[Any]       )	->							str:
           __A ,					__A		 =   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       )

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

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

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






     def      _UpperCamelCase (self     :						Tuple       )	->							int:
           # Not implemented yet for this UNet
           pass










'''simple docstring'''







import sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter






class        a__     (      TensorFormatter[Mapping, np.ndarray, Mapping]    ):
     '''simple docstring'''







     def __init__(self     :						Tuple					,					lowercase__     :						Dict=None					,					**lowercase__     :						List[Any]       )	->							str:
           super().__init__(features=lowercase__       )
           __A		 =   np_array_kwargs






     def      _UpperCamelCase (self     :						int					,					lowercase__     :						Tuple       )	->							List[Any]:
           if isinstance(lowercase__					,					lowercase__       ):
                 if column and all(
                     isinstance(lowercase__					,					np.ndarray       ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column       ):
                       return np.stack(lowercase__       )
                 else:
                       # don't use np.array(column, dtype=object)
                       # since it fails in certain cases
                       # see https://stackoverflow.com/q/51005699
                       __A		 =   np.empty(len(lowercase__       )					,					dtype=lowercase__       )
                       __A		 =   column
                       return out
           return column






     def      _UpperCamelCase (self     :						Optional[Any]					,					lowercase__     :						Optional[int]       )	->							Tuple:
           if isinstance(lowercase__					,					(str, bytes, type(lowercase__       ))       ):
                 return value
           elif isinstance(lowercase__					,					(np.character, np.ndarray)       ) and np.issubdtype(value.dtype					,					np.character       ):
                 return value
           elif isinstance(lowercase__					,					np.number       ):
                 return value

           __A		 =   {}

           if isinstance(lowercase__					,					np.ndarray       ) and np.issubdtype(value.dtype					,					np.integer       ):
                 __A		 =   {"dtype": np.intaa}
           elif isinstance(lowercase__					,					np.ndarray       ) and np.issubdtype(value.dtype					,					np.floating       ):
                 __A		 =   {"dtype": np.floataa}
           elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                 import PIL.Image

                 if isinstance(lowercase__					,					PIL.Image.Image       ):
                       return np.asarray(lowercase__					,					**self.np_array_kwargs       )

           return np.asarray(lowercase__					,					**{**default_dtype, **self.np_array_kwargs}       )






     def      _UpperCamelCase (self     :						List[Any]					,					lowercase__     :						str       )	->							Optional[Any]:
           # support for torch, tf, jax etc.
           if config.TORCH_AVAILABLE and "torch" in sys.modules:
                 import torch

                 if isinstance(lowercase__					,					torch.Tensor       ):
                       return self._tensorize(data_struct.detach().cpu().numpy()[()]       )
           if hasattr(lowercase__					,					"__array__"       ) and not isinstance(lowercase__					,					(np.ndarray, np.character, np.number)       ):
                 __A		 =   data_struct.__array__()
           # support for nested types like struct of list of struct
           if isinstance(lowercase__					,					np.ndarray       ):
                 if data_struct.dtype == object:
                       return self._consolidate([self.recursive_tensorize(lowercase__       ) for substruct in data_struct]       )
           if isinstance(lowercase__					,					(list, tuple)       ):
                 return self._consolidate([self.recursive_tensorize(lowercase__       ) for substruct in data_struct]       )
           return self._tensorize(lowercase__       )






     def      _UpperCamelCase (self     :						Optional[Any]					,					lowercase__     :						dict       )	->							Dict:
           return map_nested(self._recursive_tensorize					,					lowercase__					,					map_list=lowercase__       )






     def      _UpperCamelCase (self     :						Optional[int]					,					lowercase__     :						pa.Table       )	->							Mapping:
           __A		 =   self.numpy_arrow_extractor().extract_row(lowercase__       )
           __A		 =   self.python_features_decoder.decode_row(lowercase__       )
           return self.recursive_tensorize(lowercase__       )






     def      _UpperCamelCase (self     :						List[Any]					,					lowercase__     :						pa.Table       )	->							np.ndarray:
           __A		 =   self.numpy_arrow_extractor().extract_column(lowercase__       )
           __A		 =   self.python_features_decoder.decode_column(lowercase__					,					pa_table.column_names[0]       )
           __A		 =   self.recursive_tensorize(lowercase__       )
           __A		 =   self._consolidate(lowercase__       )
           return column






     def      _UpperCamelCase (self     :						Optional[Any]					,					lowercase__     :						pa.Table       )	->							Mapping:
           __A		 =   self.numpy_arrow_extractor().extract_batch(lowercase__       )
           __A		 =   self.python_features_decoder.decode_batch(lowercase__       )
           __A		 =   self.recursive_tensorize(lowercase__       )
           for column_name in batch:
                 __A		 =   self._consolidate(batch[column_name]       )
           return batch


