"""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     snake_case	(			__UpperCAmelCase				,   __UpperCAmelCase				,   unittest.TestCase    ):




					"""simple docstring"""

					snake_case__       =			UNetaDModel
					snake_case__       =			"sample"







					@property
					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									UpperCAmelCase__					=							4
									UpperCAmelCase__					=							14
									UpperCAmelCase__					=							16

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

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







					@property
					def 		__lowerCAmelCase						(    self       :     str      ):
									return (4, 14, 16)







					@property
					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									return (4, 14, 16)







					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									pass







					def 		__lowerCAmelCase						(    self       :     int      ):
									pass







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







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







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







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







					@unittest.skipIf(torch_device == 'mps'   ,'mish op not supported in MPS'      )
					def 		__lowerCAmelCase						(    self       :     Dict      ):
									super().test_model_from_pretrained()







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







					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									UpperCAmelCase__					=							{
									    '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',
									}
									UpperCAmelCase__					=							self.dummy_input
									return init_dict, inputs_dict







					@unittest.skipIf(torch_device == 'mps'   ,'mish op not supported in MPS'      )
					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									UpperCAmelCase__				,     UpperCAmelCase__					=							UNetaDModel.from_pretrained(
									    'bglick13/hopper-medium-v2-value-function-hor32'   ,output_loading_info=lowerCamelCase__   ,subfolder='unet'      )
									self.assertIsNotNone(lowerCamelCase__      )
									self.assertEqual(len(loading_info['missing_keys']      )   ,0      )

									model.to(lowerCamelCase__      )
									UpperCAmelCase__					=							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 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									UpperCAmelCase__					=							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      )

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

									with torch.no_grad():
													UpperCAmelCase__					=							model(lowerCamelCase__   ,lowerCamelCase__      ).sample.permute(0   ,2   ,1      )

									UpperCAmelCase__					=							output[0, -3:, -3:].flatten()
									# fmt: off
									UpperCAmelCase__					=							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(lowerCamelCase__   ,lowerCamelCase__   ,rtol=1e-3      )      )







					def 		__lowerCAmelCase						(    self       :     Optional[Any]      ):
									# Not implemented yet for this UNet
									pass







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

									UpperCAmelCase__					=							65_536
									UpperCAmelCase__					=							torch.sin(torch.arange(lowerCamelCase__      )[None, None, :].repeat(1   ,2   ,1      )      ).to(lowerCamelCase__      )
									UpperCAmelCase__					=							torch.tensor([1]      ).to(lowerCamelCase__      )

									with torch.no_grad():
													UpperCAmelCase__					=							model(lowerCamelCase__   ,lowerCamelCase__      ).sample

									UpperCAmelCase__					=							output.abs().sum()
									UpperCAmelCase__					=							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     snake_case	(			__UpperCAmelCase				,   __UpperCAmelCase				,   unittest.TestCase    ):




					"""simple docstring"""

					snake_case__       =			UNetaDModel
					snake_case__       =			"sample"







					@property
					def 		__lowerCAmelCase						(    self       :     Dict      ):
									UpperCAmelCase__					=							4
									UpperCAmelCase__					=							14
									UpperCAmelCase__					=							16

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

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







					@property
					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									return (4, 14, 16)







					@property
					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									return (4, 14, 1)







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







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







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







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







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







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

									with torch.no_grad():
													UpperCAmelCase__					=							model(**lowerCamelCase__      )

													if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
																	UpperCAmelCase__					=							output.sample

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







					def 		__lowerCAmelCase						(    self       :     List[Any]      ):
									pass







					def 		__lowerCAmelCase						(    self       :     int      ):
									pass







					def 		__lowerCAmelCase						(    self       :     Optional[Any]      ):
									UpperCAmelCase__					=							{
									    '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',
									}
									UpperCAmelCase__					=							self.dummy_input
									return init_dict, inputs_dict







					@unittest.skipIf(torch_device == 'mps'   ,'mish op not supported in MPS'      )
					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__				,     UpperCAmelCase__					=							UNetaDModel.from_pretrained(
									    'bglick13/hopper-medium-v2-value-function-hor32'   ,output_loading_info=lowerCamelCase__   ,subfolder='value_function'      )
									self.assertIsNotNone(lowerCamelCase__      )
									self.assertEqual(len(vf_loading_info['missing_keys']      )   ,0      )

									value_function.to(lowerCamelCase__      )
									UpperCAmelCase__					=							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 		__lowerCAmelCase						(    self       :     List[Any]      ):
									UpperCAmelCase__				,     UpperCAmelCase__					=							UNetaDModel.from_pretrained(
									    'bglick13/hopper-medium-v2-value-function-hor32'   ,output_loading_info=lowerCamelCase__   ,subfolder='value_function'      )
									torch.manual_seed(0      )
									if torch.cuda.is_available():
													torch.cuda.manual_seed_all(0      )

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

									with torch.no_grad():
													UpperCAmelCase__					=							value_function(lowerCamelCase__   ,lowerCamelCase__      ).sample

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







					def 		__lowerCAmelCase						(    self       :     str      ):
									# Not implemented yet for this UNet
									pass




"""simple docstring"""






from sklearn.metrics import accuracy_score

import datasets


lowerCAmelCase__  :  List[str]											=     '\nAccuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:\nAccuracy = (TP + TN) / (TP + TN + FP + FN)\n Where:\nTP: True positive\nTN: True negative\nFP: False positive\nFN: False negative\n'


lowerCAmelCase__  :  List[str]											=     '\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.\n\nExamples:\n\n    Example 1-A simple example\n        >>> accuracy_metric = datasets.load_metric("accuracy")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])\n        >>> print(results)\n        {\'accuracy\': 0.5}\n\n    Example 2-The same as Example 1, except with `normalize` set to `False`.\n        >>> accuracy_metric = datasets.load_metric("accuracy")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)\n        >>> print(results)\n        {\'accuracy\': 3.0}\n\n    Example 3-The same as Example 1, except with `sample_weight` set.\n        >>> accuracy_metric = datasets.load_metric("accuracy")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])\n        >>> print(results)\n        {\'accuracy\': 0.8778625954198473}\n'


lowerCAmelCase__  :  Dict											=     '\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,   _KWARGS_DESCRIPTION    )
class     snake_case	(			datasets.Metric    ):




					"""simple docstring"""

					def 		__lowerCAmelCase						(    self       :     List[Any]      ):
									return datasets.MetricInfo(
									    description=_DESCRIPTION   ,citation=_CITATION   ,inputs_description=_KWARGS_DESCRIPTION   ,features=datasets.Features(
									        {
									            'predictions': datasets.Sequence(datasets.Value('int32'      )      ),
									            'references': datasets.Sequence(datasets.Value('int32'      )      ),
									        }
									        if self.config_name == 'multilabel'
									        else {
									            'predictions': datasets.Value('int32'      ),
									            'references': datasets.Value('int32'      ),
									        }      )   ,reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html']   ,)







					def 		__lowerCAmelCase						(    self       :     int   ,lowerCamelCase__       :     Any   ,lowerCamelCase__       :     List[str]   ,lowerCamelCase__       :     Dict=True   ,lowerCamelCase__       :     Tuple=None      ):
									return {
									    "accuracy": float(
									        accuracy_score(lowerCamelCase__   ,lowerCamelCase__   ,normalize=lowerCamelCase__   ,sample_weight=lowerCamelCase__      )      )
									}



