


'''simple docstring'''



import gc
import inspect
import unittest

import torch
from parameterized import parameterized

from diffusers import PriorTransformer
from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin


enable_full_determinism()



class 			a       (	_a			,						unittest.TestCase ):


     """simple docstring"""






     SCREAMING_SNAKE_CASE :				Optional[Any]							     =     PriorTransformer
     SCREAMING_SNAKE_CASE :				Optional[Any]							     =     "hidden_states"

     @property
     def 				lowerCamelCase__				(       self  :	Union[str, Any]    )		->							Optional[int]:
          __UpperCAmelCase			:				Any													=    4
          __UpperCAmelCase			:				Any													=    8
          __UpperCAmelCase			:				Dict													=    7

          __UpperCAmelCase			:				Tuple													=    floats_tensor((batch_size, embedding_dim)    ).to(snake_case    )

          __UpperCAmelCase			:				Union[str, Any]													=    floats_tensor((batch_size, embedding_dim)    ).to(snake_case    )
          __UpperCAmelCase			:				Tuple													=    floats_tensor((batch_size, num_embeddings, embedding_dim)    ).to(snake_case    )

          return {
              "hidden_states": hidden_states,
              "timestep": 2,
              "proj_embedding": proj_embedding,
              "encoder_hidden_states": encoder_hidden_states,
          }

     def 				lowerCamelCase__				(       self  :	Any							,				snake_case  :	Tuple=0    )		->							str:
          torch.manual_seed(snake_case    )
          __UpperCAmelCase			:				Dict													=    4
          __UpperCAmelCase			:				Optional[int]													=    8
          __UpperCAmelCase			:				List[Any]													=    7

          __UpperCAmelCase			:				List[str]													=    torch.randn((batch_size, embedding_dim)    ).to(snake_case    )

          __UpperCAmelCase			:				int													=    torch.randn((batch_size, embedding_dim)    ).to(snake_case    )
          __UpperCAmelCase			:				Any													=    torch.randn((batch_size, num_embeddings, embedding_dim)    ).to(snake_case    )

          return {
              "hidden_states": hidden_states,
              "timestep": 2,
              "proj_embedding": proj_embedding,
              "encoder_hidden_states": encoder_hidden_states,
          }

     @property
     def 				lowerCamelCase__				(       self  :	Tuple    )		->							int:
          return (4, 8)

     @property
     def 				lowerCamelCase__				(       self  :	Optional[Any]    )		->							str:
          return (4, 8)

     def 				lowerCamelCase__				(       self  :	int    )		->							Optional[int]:
          __UpperCAmelCase			:				str													=    {
              '''num_attention_heads''': 2,
              '''attention_head_dim''': 4,
              '''num_layers''': 2,
              '''embedding_dim''': 8,
              '''num_embeddings''': 7,
              '''additional_embeddings''': 4,
          }
          __UpperCAmelCase			:				Tuple													=    self.dummy_input
          return init_dict, inputs_dict

     def 				lowerCamelCase__				(       self  :	str    )		->							Any:
          __UpperCAmelCase							,     __UpperCAmelCase			:				Any													=    PriorTransformer.from_pretrained(
              '''hf-internal-testing/prior-dummy'''							,				output_loading_info=snake_case    )
          self.assertIsNotNone(snake_case    )
          self.assertEqual(len(loading_info['''missing_keys''']    )							,				0    )

          model.to(snake_case    )
          __UpperCAmelCase			:				Tuple													=    model(**self.dummy_input    )[0]

          assert hidden_states is not None, "Make sure output is not None"

     def 				lowerCamelCase__				(       self  :	Optional[Any]    )		->							str:
          __UpperCAmelCase							,     __UpperCAmelCase			:				Any													=    self.prepare_init_args_and_inputs_for_common()

          __UpperCAmelCase			:				Tuple													=    self.model_class(**snake_case    )
          __UpperCAmelCase			:				Optional[Any]													=    inspect.signature(model.forward    )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          __UpperCAmelCase			:				int													=    [*signature.parameters.keys()]

          __UpperCAmelCase			:				Union[str, Any]													=    ['''hidden_states''', '''timestep''']
          self.assertListEqual(arg_names[:2]							,				snake_case    )






     def 				lowerCamelCase__				(       self  :	List[Any]    )		->							Any:
          __UpperCAmelCase			:				Any													=    PriorTransformer.from_pretrained('''hf-internal-testing/prior-dummy'''    )
          __UpperCAmelCase			:				List[str]													=    model.to(snake_case    )

          if hasattr(snake_case							,				'''set_default_attn_processor'''    ):
               model.set_default_attn_processor()

          __UpperCAmelCase			:				int													=    self.get_dummy_seed_input()

          with torch.no_grad():
               __UpperCAmelCase			:				Any													=    model(**snake_case    )[0]

          __UpperCAmelCase			:				Optional[Any]													=    output[0, :5].flatten().cpu()
          print(snake_case    )

          # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
          # the expected output slices are not the same for CPU and GPU.
          __UpperCAmelCase			:				Any													=    torch.tensor([-1.3_436, -0.2_870, 0.7_538, 0.4_368, -0.0_239]    )
          self.assertTrue(torch_all_close(snake_case							,				snake_case							,				rtol=1E-2    )    )



@slow
class 			a       (	unittest.TestCase ):


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	str							,				snake_case  :	Union[str, Any]=1							,				snake_case  :	Optional[Any]=768							,				snake_case  :	int=77							,				snake_case  :	Dict=0    )		->							Dict:
          torch.manual_seed(snake_case    )
          __UpperCAmelCase			:				int													=    batch_size
          __UpperCAmelCase			:				Any													=    embedding_dim
          __UpperCAmelCase			:				Optional[Any]													=    num_embeddings

          __UpperCAmelCase			:				Union[str, Any]													=    torch.randn((batch_size, embedding_dim)    ).to(snake_case    )

          __UpperCAmelCase			:				List[Any]													=    torch.randn((batch_size, embedding_dim)    ).to(snake_case    )
          __UpperCAmelCase			:				Optional[int]													=    torch.randn((batch_size, num_embeddings, embedding_dim)    ).to(snake_case    )

          return {
              "hidden_states": hidden_states,
              "timestep": 2,
              "proj_embedding": proj_embedding,
              "encoder_hidden_states": encoder_hidden_states,
          }

     def 				lowerCamelCase__				(       self  :	str    )		->							List[Any]:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






     @parameterized.expand(
         [
             # fmt: off
             [13, [-0.5_861,  0.1_283, -0.0_931,  0.0_882,  0.4_476,  0.1_329, -0.0_498,  0.0_640]],
             [37, [-0.4_913,  0.0_110, -0.0_483,  0.0_541,  0.4_954, -0.0_170,  0.0_354,  0.1_651]],
             # fmt: on
         ]    )
     def 				lowerCamelCase__				(       self  :	List[str]							,				snake_case  :	Dict							,				snake_case  :	str    )		->							List[str]:
          __UpperCAmelCase			:				Any													=    PriorTransformer.from_pretrained('''kandinsky-community/kandinsky-2-1-prior'''							,				subfolder='''prior'''    )
          model.to(snake_case    )
          __UpperCAmelCase			:				Any													=    self.get_dummy_seed_input(seed=snake_case    )

          with torch.no_grad():
               __UpperCAmelCase			:				List[str]													=    model(**snake_case    )[0]

          assert list(sample.shape    ) == [1, 768]

          __UpperCAmelCase			:				List[str]													=    sample[0, :8].flatten().cpu()
          print(snake_case    )
          __UpperCAmelCase			:				List[str]													=    torch.tensor(snake_case    )

          assert torch_all_close(snake_case							,				snake_case							,				atol=1E-3    )



'''simple docstring'''



from scipy.stats import pearsonr

import datasets


__UpperCAmelCase    :Tuple				       =     "\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n"


__UpperCAmelCase    :List[str]				       =     "\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results['pearsonr'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        ['p-value', 'pearsonr']\n        >>> print(round(results['pearsonr'], 2))\n        -0.74\n        >>> print(round(results['p-value'], 2))\n        0.15\n"


__UpperCAmelCase    :List[Any]				       =     "\n@article{2020SciPy-NMeth,\nauthor  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n      Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n      Kern, Robert and Larson, Eric and Carey, C J and\n      Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n      Harris, Charles R. and Archibald, Anne M. and\n      Ribeiro, Antonio H. and Pedregosa, Fabian and\n      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n      Computing in Python}},\njournal = {Nature Methods},\nyear    = {2020},\nvolume  = {17},\npages   = {261--272},\nadsurl  = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n"



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,						_KWARGS_DESCRIPTION )
class 			a       (	datasets.Metric ):


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	List[Any]    )		->							Union[str, Any]:
          return datasets.MetricInfo(
              description=_DESCRIPTION							,				citation=_CITATION							,				inputs_description=_KWARGS_DESCRIPTION							,				features=datasets.Features(
                  {
                      '''predictions''': datasets.Value('''float'''    ),
                      '''references''': datasets.Value('''float'''    ),
                  }    )							,				reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html''']							,				)






     def 				lowerCamelCase__				(       self  :	Any							,				snake_case  :	Union[str, Any]							,				snake_case  :	int							,				snake_case  :	Dict=False    )		->							List[Any]:
          if return_pvalue:
               __UpperCAmelCase			:				Tuple													=    pearsonr(snake_case							,				snake_case    )
               return {"pearsonr": results[0], "p-value": results[1]}
          else:
               return {"pearsonr": float(pearsonr(snake_case							,				snake_case    )[0]    )}