




'''simple docstring'''



import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 							__SCREAMING_SNAKE_CASE       (							_lowerCAmelCase      ,      unittest.TestCase     ):
      __a  					=ConsistencyModelPipeline
      __a  					=UNCONDITIONAL_IMAGE_GENERATION_PARAMS
      __a  					=UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

      # Override required_optional_params to remove num_images_per_prompt
      __a  					=frozenset(
          [
              "num_inference_steps",
              "generator",
              "latents",
              "output_type",
              "return_dict",
              "callback",
              "callback_steps",
          ]     )




      @property
      def  __UpperCamelCase							(  self      )							->Optional[int]:



         '''simple docstring'''
         __a				     =    UNetaDModel.from_pretrained(
             'diffusers/consistency-models-test' ,   subfolder='test_unet' ,   )
         return unet




      @property
      def  __UpperCamelCase							(  self      )							->str:



         '''simple docstring'''
         __a				     =    UNetaDModel.from_pretrained(
             'diffusers/consistency-models-test' ,   subfolder='test_unet_class_cond' ,   )
         return unet




      def  __UpperCamelCase							(  self ,   lowerCamelCase=False      )							->int:



         '''simple docstring'''
         if class_cond:
            __a				     =    self.dummy_cond_unet
         else:
            __a				     =    self.dummy_uncond_unet

         # Default to CM multistep sampler
         __a				     =    CMStochasticIterativeScheduler(
             num_train_timesteps=40 ,   sigma_min=0.002 ,   sigma_max=80.0 ,   )

         __a				     =    {
             'unet': unet,
             'scheduler': scheduler,
         }

         return components




      def  __UpperCamelCase							(  self ,   lowerCamelCase ,   lowerCamelCase=0      )							->Optional[int]:



         '''simple docstring'''
         if str(lowerCamelCase      ).startswith('mps'      ):
            __a				     =    torch.manual_seed(lowerCamelCase      )
         else:
            __a				     =    torch.Generator(device=lowerCamelCase      ).manual_seed(lowerCamelCase      )

         __a				     =    {
             'batch_size': 1,
             'num_inference_steps': None,
             'timesteps': [22, 0],
             'generator': generator,
             'output_type': 'np',
         }

         return inputs




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    'cpu'  # ensure determinism for the device-dependent torch.Generator
         __a				     =    self.get_dummy_components()
         __a				     =    ConsistencyModelPipeline(**lowerCamelCase      )
         __a				     =    pipe.to(lowerCamelCase      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_dummy_inputs(lowerCamelCase      )
         __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 32, 32, 3)

         __a				     =    image[0, -3:, -3:, -1]
         __a				     =    np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3




      def  __UpperCamelCase							(  self      )							->List[str]:



         '''simple docstring'''
         __a				     =    'cpu'  # ensure determinism for the device-dependent torch.Generator
         __a				     =    self.get_dummy_components(class_cond=lowerCamelCase      )
         __a				     =    ConsistencyModelPipeline(**lowerCamelCase      )
         __a				     =    pipe.to(lowerCamelCase      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_dummy_inputs(lowerCamelCase      )
         __a				     =    0
         __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 32, 32, 3)

         __a				     =    image[0, -3:, -3:, -1]
         __a				     =    np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3




      def  __UpperCamelCase							(  self      )							->Optional[int]:



         '''simple docstring'''
         __a				     =    'cpu'  # ensure determinism for the device-dependent torch.Generator
         __a				     =    self.get_dummy_components()
         __a				     =    ConsistencyModelPipeline(**lowerCamelCase      )
         __a				     =    pipe.to(lowerCamelCase      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_dummy_inputs(lowerCamelCase      )
         __a				     =    1
         __a				     =    None
         __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 32, 32, 3)

         __a				     =    image[0, -3:, -3:, -1]
         __a				     =    np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3






      def  __UpperCamelCase							(  self      )							->List[Any]:



         '''simple docstring'''
         __a				     =    'cpu'  # ensure determinism for the device-dependent torch.Generator
         __a				     =    self.get_dummy_components(class_cond=lowerCamelCase      )
         __a				     =    ConsistencyModelPipeline(**lowerCamelCase      )
         __a				     =    pipe.to(lowerCamelCase      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_dummy_inputs(lowerCamelCase      )
         __a				     =    1
         __a				     =    None
         __a				     =    0
         __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 32, 32, 3)

         __a				     =    image[0, -3:, -3:, -1]
         __a				     =    np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3







@slow
@require_torch_gpu
class 							__SCREAMING_SNAKE_CASE       (							unittest.TestCase     ):




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




      def  __UpperCamelCase							(  self ,   lowerCamelCase=0 ,   lowerCamelCase=False ,   lowerCamelCase="cpu" ,   lowerCamelCase=torch.floataa ,   lowerCamelCase=(1, 3, 64, 64)      )							->List[Any]:



         '''simple docstring'''
         __a				     =    torch.manual_seed(lowerCamelCase      )

         __a				     =    {
             'num_inference_steps': None,
             'timesteps': [22, 0],
             'class_labels': 0,
             'generator': generator,
             'output_type': 'np',
         }

         if get_fixed_latents:
            __a				     =    self.get_fixed_latents(seed=lowerCamelCase ,   device=lowerCamelCase ,   dtype=lowerCamelCase ,   shape=lowerCamelCase      )
            __a				     =    latents

         return inputs




      def  __UpperCamelCase							(  self ,   lowerCamelCase=0 ,   lowerCamelCase="cpu" ,   lowerCamelCase=torch.floataa ,   lowerCamelCase=(1, 3, 64, 64)      )							->Union[str, Any]:



         '''simple docstring'''
         if type(lowerCamelCase      ) == str:
            __a				     =    torch.device(lowerCamelCase      )
         __a				     =    torch.Generator(device=lowerCamelCase      ).manual_seed(lowerCamelCase      )
         __a				     =    randn_tensor(lowerCamelCase ,   generator=lowerCamelCase ,   device=lowerCamelCase ,   dtype=lowerCamelCase      )
         return latents




      def  __UpperCamelCase							(  self      )							->Tuple:



         '''simple docstring'''
         __a				     =    UNetaDModel.from_pretrained('diffusers/consistency_models' ,   subfolder='diffusers_cd_imagenet64_l2'      )
         __a				     =    CMStochasticIterativeScheduler(
             num_train_timesteps=40 ,   sigma_min=0.002 ,   sigma_max=80.0 ,   )
         __a				     =    ConsistencyModelPipeline(unet=lowerCamelCase ,   scheduler=lowerCamelCase      )
         pipe.to(torch_device=lowerCamelCase      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_inputs()
         __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 64, 64, 3)

         __a				     =    image[0, -3:, -3:, -1]

         __a				     =    np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 2e-2




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



         '''simple docstring'''
         __a				     =    UNetaDModel.from_pretrained('diffusers/consistency_models' ,   subfolder='diffusers_cd_imagenet64_l2'      )
         __a				     =    CMStochasticIterativeScheduler(
             num_train_timesteps=40 ,   sigma_min=0.002 ,   sigma_max=80.0 ,   )
         __a				     =    ConsistencyModelPipeline(unet=lowerCamelCase ,   scheduler=lowerCamelCase      )
         pipe.to(torch_device=lowerCamelCase      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_inputs()
         __a				     =    1
         __a				     =    None
         __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 64, 64, 3)

         __a				     =    image[0, -3:, -3:, -1]

         __a				     =    np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 2e-2




      @require_torch_a
      def  __UpperCamelCase							(  self      )							->Optional[int]:



         '''simple docstring'''
         __a				     =    UNetaDModel.from_pretrained('diffusers/consistency_models' ,   subfolder='diffusers_cd_imagenet64_l2'      )
         __a				     =    CMStochasticIterativeScheduler(
             num_train_timesteps=40 ,   sigma_min=0.002 ,   sigma_max=80.0 ,   )
         __a				     =    ConsistencyModelPipeline(unet=lowerCamelCase ,   scheduler=lowerCamelCase      )
         pipe.to(torch_device=lowerCamelCase ,   torch_dtype=torch.floataa      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_inputs(get_fixed_latents=lowerCamelCase ,   device=lowerCamelCase      )
         # Ensure usage of flash attention in torch 2.0
         with sdp_kernel(enable_flash=lowerCamelCase ,   enable_math=lowerCamelCase ,   enable_mem_efficient=lowerCamelCase      ):
            __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 64, 64, 3)

         __a				     =    image[0, -3:, -3:, -1]

         __a				     =    np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3






      @require_torch_a
      def  __UpperCamelCase							(  self      )							->List[str]:



         '''simple docstring'''
         __a				     =    UNetaDModel.from_pretrained('diffusers/consistency_models' ,   subfolder='diffusers_cd_imagenet64_l2'      )
         __a				     =    CMStochasticIterativeScheduler(
             num_train_timesteps=40 ,   sigma_min=0.002 ,   sigma_max=80.0 ,   )
         __a				     =    ConsistencyModelPipeline(unet=lowerCamelCase ,   scheduler=lowerCamelCase      )
         pipe.to(torch_device=lowerCamelCase ,   torch_dtype=torch.floataa      )
         pipe.set_progress_bar_config(disable=lowerCamelCase      )

         __a				     =    self.get_inputs(get_fixed_latents=lowerCamelCase ,   device=lowerCamelCase      )
         __a				     =    1
         __a				     =    None
         # Ensure usage of flash attention in torch 2.0
         with sdp_kernel(enable_flash=lowerCamelCase ,   enable_math=lowerCamelCase ,   enable_mem_efficient=lowerCamelCase      ):
            __a				     =    pipe(**lowerCamelCase      ).images
         assert image.shape == (1, 64, 64, 3)

         __a				     =    image[0, -3:, -3:, -1]

         __a				     =    np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095]      )

         assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1e-3







'''simple docstring'''



import datasets

from .evaluate import evaluate


__UpperCamelCase      :       int      			=      """\
@article{hendrycks2021cuad,
      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},
      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},
      journal={arXiv preprint arXiv:2103.06268},
      year={2021}
}
"""

__UpperCamelCase      :       int      			=      """
This metric wrap the official scoring script for version 1 of the Contract
Understanding Atticus Dataset (CUAD).
Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510
commercial legal contracts that have been manually labeled to identify 41 categories of important
clauses that lawyers look for when reviewing contracts in connection with corporate transactions.
"""

__UpperCamelCase      :       str      			=      """
Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair as given in the references (see below)
        - 'prediction_text': list of possible texts for the answer, as a list of strings
        depending on a threshold on the confidence probability of each prediction.
    references: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair (see above),
        - 'answers': a Dict in the CUAD dataset format
            {
                'text': list of possible texts for the answer, as a list of strings
                'answer_start': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    'exact_match': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
    'aupr': Area Under the Precision-Recall curve
    'prec_at_80_recall': Precision at 80% recall
    'prec_at_90_recall': Precision at 90% recall
Examples:
    >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]
    >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]
    >>> cuad_metric = datasets.load_metric(\"cuad\")
    >>> results = cuad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,      _KWARGS_DESCRIPTION     )
class 							__SCREAMING_SNAKE_CASE       (							datasets.Metric     ):




      def  __UpperCamelCase							(  self      )							->Optional[Any]:



         '''simple docstring'''
         return datasets.MetricInfo(
             description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
                 {
                     'predictions': {
                         'id': datasets.Value('string'      ),
                         'prediction_text': datasets.features.Sequence(datasets.Value('string'      )      ),
                     },
                     'references': {
                         'id': datasets.Value('string'      ),
                         'answers': datasets.features.Sequence(
                             {
                                 'text': datasets.Value('string'      ),
                                 'answer_start': datasets.Value('int32'      ),
                             }      ),
                     },
                 }      ) ,   codebase_urls=['https://www.atticusprojectai.org/cuad'] ,   reference_urls=['https://www.atticusprojectai.org/cuad'] ,   )






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



         '''simple docstring'''
         __a				     =    {prediction['id']: prediction['prediction_text'] for prediction in predictions}
         __a				     =    [
             {
                 'paragraphs': [
                     {
                         'qas': [
                             {
                                 'answers': [{'text': answer_text} for answer_text in ref['answers']['text']],
                                 'id': ref['id'],
                             }
                             for ref in references
                         ]
                     }
                 ]
             }
         ]
         __a				     =    evaluate(dataset=lowerCamelCase ,   predictions=lowerCamelCase      )
         return score