






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


     UpperCamelCase_				:		List[str]								=						PriorTransformer
     UpperCamelCase_				:		Union[str, Any]								=						'''hidden_states'''


     @property
     def 					_A							(					self							:						Dict   ):
       SCREAMING_SNAKE_CASE							:   List[str]						    =     4
       SCREAMING_SNAKE_CASE							:   Dict						    =     8
       SCREAMING_SNAKE_CASE							:   List[str]						    =     7

       SCREAMING_SNAKE_CASE							:   str						    =     floats_tensor((batch_size, embedding_dim)   ).to(UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   List[str]						    =     floats_tensor((batch_size, embedding_dim)   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Any						    =     floats_tensor((batch_size, num_embeddings, embedding_dim)   ).to(UpperCAmelCase_   )

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


     def 					_A							(					self							:						Optional[Any]       ,			UpperCAmelCase_							:						Tuple=0   ):
       torch.manual_seed(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Dict						    =     4
       SCREAMING_SNAKE_CASE							:   int						    =     8
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     7

       SCREAMING_SNAKE_CASE							:   int						    =     torch.randn((batch_size, embedding_dim)   ).to(UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   Tuple						    =     torch.randn((batch_size, embedding_dim)   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     torch.randn((batch_size, num_embeddings, embedding_dim)   ).to(UpperCAmelCase_   )

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


     @property
     def 					_A							(					self							:						Optional[Any]   ):
       return (4, 8)


     @property
     def 					_A							(					self							:						Any   ):
       return (4, 8)


     def 					_A							(					self							:						int   ):
       SCREAMING_SNAKE_CASE							:   Optional[int]						    =     {
           "num_attention_heads": 2,
           "attention_head_dim": 4,
           "num_layers": 2,
           "embedding_dim": 8,
           "num_embeddings": 7,
           "additional_embeddings": 4,
       }
       SCREAMING_SNAKE_CASE							:   Dict						    =     self.dummy_input
       return init_dict, inputs_dict


     def 					_A							(					self							:						Optional[int]   ):
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   Tuple						    =     PriorTransformer.from_pretrained(
           "hf-internal-testing/prior-dummy"       ,			output_loading_info=UpperCAmelCase_   )
       self.assertIsNotNone(UpperCAmelCase_   )
       self.assertEqual(len(loading_info["missing_keys"]   )       ,			0   )

       model.to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   int						    =     model(**self.dummy_input   )[0]

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


     def 					_A							(					self							:						Any   ):
       SCREAMING_SNAKE_CASE    ,	SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     self.prepare_init_args_and_inputs_for_common()

       SCREAMING_SNAKE_CASE							:   Tuple						    =     self.model_class(**UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   str						    =     inspect.signature(model.forward   )
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       SCREAMING_SNAKE_CASE							:   Dict						    =     [*signature.parameters.keys()]

       SCREAMING_SNAKE_CASE							:   List[Any]						    =     ["hidden_states", "timestep"]
       self.assertListEqual(arg_names[:2]       ,			UpperCAmelCase_   )






     def 					_A							(					self							:						Optional[int]   ):
       SCREAMING_SNAKE_CASE							:   Dict						    =     PriorTransformer.from_pretrained("hf-internal-testing/prior-dummy"   )
       SCREAMING_SNAKE_CASE							:   str						    =     model.to(UpperCAmelCase_   )

       if hasattr(UpperCAmelCase_       ,			"set_default_attn_processor"   ):
         model.set_default_attn_processor()

       SCREAMING_SNAKE_CASE							:   List[str]						    =     self.get_dummy_seed_input()

       with torch.no_grad():
         SCREAMING_SNAKE_CASE							:   List[Any]						    =     model(**UpperCAmelCase_   )[0]

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

       # 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.
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     torch.tensor([-1.3_436, -0.2_870, 0.7_538, 0.4_368, -0.0_239]   )
       self.assertTrue(torch_all_close(UpperCAmelCase_       ,			UpperCAmelCase_       ,			rtol=1E-2   )   )





@slow
class 			SCREAMING_SNAKE_CASE      (      unittest.TestCase       ):
     '''simple docstring'''


     def 					_A							(					self							:						str       ,			UpperCAmelCase_							:						Dict=1       ,			UpperCAmelCase_							:						Optional[int]=768       ,			UpperCAmelCase_							:						List[str]=77       ,			UpperCAmelCase_							:						List[Any]=0   ):
       torch.manual_seed(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     batch_size
       SCREAMING_SNAKE_CASE							:   int						    =     embedding_dim
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     num_embeddings

       SCREAMING_SNAKE_CASE							:   Tuple						    =     torch.randn((batch_size, embedding_dim)   ).to(UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   Any						    =     torch.randn((batch_size, embedding_dim)   ).to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Any						    =     torch.randn((batch_size, num_embeddings, embedding_dim)   ).to(UpperCAmelCase_   )

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


     def 					_A							(					self							:						int   ):
       # 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 					_A							(					self							:						List[Any]       ,			UpperCAmelCase_							:						str       ,			UpperCAmelCase_							:						List[str]   ):
       SCREAMING_SNAKE_CASE							:   int						    =     PriorTransformer.from_pretrained("kandinsky-community/kandinsky-2-1-prior"       ,			subfolder="prior"   )
       model.to(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     self.get_dummy_seed_input(seed=UpperCAmelCase_   )

       with torch.no_grad():
         SCREAMING_SNAKE_CASE							:   str						    =     model(**UpperCAmelCase_   )[0]

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

       SCREAMING_SNAKE_CASE							:   Optional[int]						    =     sample[0, :8].flatten().cpu()
       print(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   List[Any]						    =     torch.tensor(UpperCAmelCase_   )

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













'''simple docstring'''


import re
import string

import numpy as np

import datasets


_SCREAMING_SNAKE_CASE									=				"\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n"

_SCREAMING_SNAKE_CASE									=				"\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    33.3\n\n"

_SCREAMING_SNAKE_CASE									=				"\n"

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




 def 				_snake_case (						self		)     ->				List[str]:
     return datasets.MetricInfo(
         description=_DESCRIPTION      ,  citation=_CITATION      ,  inputs_description=_KWARGS_DESCRIPTION      ,  features=datasets.Features(
             {
                 "predictions": datasets.Value("string"      ,  id="sequence"		),
                 "references": datasets.Value("string"      ,  id="sequence"		),
             }		)      ,  reference_urls=[]      ,  )





 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase=None      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=False      ,  )     ->				str:
     if regexes_to_ignore is not None:
         for s in regexes_to_ignore:
             _lowerCAmelCase						      =   np.array([re.sub(_lowerCAmelCase      ,  ""      ,  _lowerCAmelCase		) for x in predictions]		)
             _lowerCAmelCase						      =   np.array([re.sub(_lowerCAmelCase      ,  ""      ,  _lowerCAmelCase		) for x in references]		)
     else:
         _lowerCAmelCase						      =   np.asarray(_lowerCAmelCase		)
         _lowerCAmelCase						      =   np.asarray(_lowerCAmelCase		)

     if ignore_case:
         _lowerCAmelCase						      =   np.char.lower(_lowerCAmelCase		)
         _lowerCAmelCase						      =   np.char.lower(_lowerCAmelCase		)

     if ignore_punctuation:
         _lowerCAmelCase						      =   string.punctuation.maketrans(""      ,  ""      ,  string.punctuation		)
         _lowerCAmelCase						      =   np.char.translate(_lowerCAmelCase      ,  table=_lowerCAmelCase		)
         _lowerCAmelCase						      =   np.char.translate(_lowerCAmelCase      ,  table=_lowerCAmelCase		)

     if ignore_numbers:
         _lowerCAmelCase						      =   string.digits.maketrans(""      ,  ""      ,  string.digits		)
         _lowerCAmelCase						      =   np.char.translate(_lowerCAmelCase      ,  table=_lowerCAmelCase		)
         _lowerCAmelCase						      =   np.char.translate(_lowerCAmelCase      ,  table=_lowerCAmelCase		)

     _lowerCAmelCase						      =   predictions == references

     return {"exact_match": np.mean(_lowerCAmelCase		) * 100}


