





"""simple docstring"""
import re
import string
from collections import Counter

import sacrebleu
import sacremoses
from packaging import version

import datasets


lowerCamelCase_								=		"\n@inproceedings{xu-etal-2016-optimizing,\n    title = {Optimizing Statistical Machine Translation for Text Simplification},\n    authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n    journal = {Transactions of the Association for Computational Linguistics},\n    volume = {4},\n    year={2016},\n    url = {https://www.aclweb.org/anthology/Q16-1029},\n    pages = {401--415\n},\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

lowerCamelCase_								=		"\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n"


lowerCamelCase_								=		"\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n    sources: list of source sentences where each sentence should be a string.\n    predictions: list of predicted sentences where each sentence should be a string.\n    references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n    sari: sari score\n    sacrebleu: sacrebleu score\n    exact: exact score\n\nExamples:\n    >>> sources=[\"About 95 species are currently accepted .\"]\n    >>> predictions=[\"About 95 you now get in .\"]\n    >>> references=[[\"About 95 species are currently known .\"]]\n    >>> wiki_split = datasets.load_metric(\"wiki_split\")\n    >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n    >>> print(results)\n    {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0}\n"



def      __lowerCamelCase   (							a_     :		List[str]							)			->      Optional[Any]:

      def remove_articles(a_     :		List[str]							):
            __SCREAMING_SNAKE_CASE   :List[str]						=  re.compile(r'''\b(a|an|the)\b''' ,   re.UNICODE							)
            return re.sub(a_ ,   ''' ''' ,   a_							)

      def white_space_fix(a_     :		Union[str, Any]							):
            return " ".join(text.split()							)

      def remove_punc(a_     :		str							):
            __SCREAMING_SNAKE_CASE   :List[str]						=  set(string.punctuation							)
            return "".join(ch for ch in text if ch not in exclude							)

      def lower(a_     :		Tuple							):
            return text.lower()

      return white_space_fix(remove_articles(remove_punc(lower(a_							)							)							)							)



def      __lowerCamelCase   (							a_     :		Union[str, Any] ,   a_     :		Optional[Any]							)			->      Optional[int]:
      return int(normalize_answer(a_							) == normalize_answer(a_							)							)



def      __lowerCamelCase   (							a_     :		int ,   a_     :		Optional[int]							)			->      Any:
      __SCREAMING_SNAKE_CASE   :Tuple						=  [any(compute_exact(a_ ,   a_							) for ref in refs							) for pred, refs in zip(a_ ,   a_							)]
      return (sum(a_							) / len(a_							)) * 1_00



def      __lowerCamelCase   (							a_     :		Optional[int] ,   a_     :		Optional[int] ,   a_     :		Tuple ,   a_     :		Optional[int]							)			->      List[str]:
      __SCREAMING_SNAKE_CASE   :Tuple						=  [rgram for rgrams in rgramslist for rgram in rgrams]
      __SCREAMING_SNAKE_CASE   :str						=  Counter(a_							)

      __SCREAMING_SNAKE_CASE   :Tuple						=  Counter(a_							)
      __SCREAMING_SNAKE_CASE   :str						=  Counter()
      for sgram, scount in sgramcounter.items():
            __SCREAMING_SNAKE_CASE   :List[str]						=  scount * numref

      __SCREAMING_SNAKE_CASE   :Any						=  Counter(a_							)
      __SCREAMING_SNAKE_CASE   :Tuple						=  Counter()
      for cgram, ccount in cgramcounter.items():
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  ccount * numref

      # KEEP
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  sgramcounter_rep & cgramcounter_rep
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  keepgramcounter_rep & rgramcounter
      __SCREAMING_SNAKE_CASE   :Dict						=  sgramcounter_rep & rgramcounter

      __SCREAMING_SNAKE_CASE   :str						=  0
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  0
      for keepgram in keepgramcountergood_rep:
            keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
            # Fix an alleged bug [2] in the keep score computation.
            # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
            keeptmpscorea += keepgramcountergood_rep[keepgram]
      # Define 0/0=1 instead of 0 to give higher scores for predictions that match
      #      a target exactly.
      __SCREAMING_SNAKE_CASE   :Any						=  1
      __SCREAMING_SNAKE_CASE   :int						=  1
      if len(a_							) > 0:
            __SCREAMING_SNAKE_CASE   :Optional[int]						=  keeptmpscorea / len(a_							)
      if len(a_							) > 0:
            # Fix an alleged bug [2] in the keep score computation.
            # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
            __SCREAMING_SNAKE_CASE   :List[Any]						=  keeptmpscorea / sum(keepgramcounterall_rep.values()							)
      __SCREAMING_SNAKE_CASE   :List[str]						=  0
      if keepscore_precision > 0 or keepscore_recall > 0:
            __SCREAMING_SNAKE_CASE   :int						=  2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)

      # DELETION
      __SCREAMING_SNAKE_CASE   :List[Any]						=  sgramcounter_rep - cgramcounter_rep
      __SCREAMING_SNAKE_CASE   :int						=  delgramcounter_rep - rgramcounter
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  sgramcounter_rep - rgramcounter
      __SCREAMING_SNAKE_CASE   :List[Any]						=  0
      __SCREAMING_SNAKE_CASE   :List[str]						=  0
      for delgram in delgramcountergood_rep:
            deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
            deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
      # Define 0/0=1 instead of 0 to give higher scores for predictions that match
      # a target exactly.
      __SCREAMING_SNAKE_CASE   :Dict						=  1
      if len(a_							) > 0:
            __SCREAMING_SNAKE_CASE   :Any						=  deltmpscorea / len(a_							)

      # ADDITION
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  set(a_							) - set(a_							)
      __SCREAMING_SNAKE_CASE   :str						=  set(a_							) & set(a_							)
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  set(a_							) - set(a_							)

      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  0
      for addgram in addgramcountergood:
            addtmpscore += 1

      # Define 0/0=1 instead of 0 to give higher scores for predictions that match
      # a target exactly.
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  1
      __SCREAMING_SNAKE_CASE   :List[str]						=  1
      if len(a_							) > 0:
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  addtmpscore / len(a_							)
      if len(a_							) > 0:
            __SCREAMING_SNAKE_CASE   :List[Any]						=  addtmpscore / len(a_							)
      __SCREAMING_SNAKE_CASE   :Tuple						=  0
      if addscore_precision > 0 or addscore_recall > 0:
            __SCREAMING_SNAKE_CASE   :Optional[Any]						=  2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)

      return (keepscore, delscore_precision, addscore)



def      __lowerCamelCase   (							a_     :		Any ,   a_     :		List[Any] ,   a_     :		str							)			->      Any:
      __SCREAMING_SNAKE_CASE   :int						=  len(a_							)

      __SCREAMING_SNAKE_CASE   :int						=  ssent.split(''' '''							)
      __SCREAMING_SNAKE_CASE   :Dict						=  csent.split(''' '''							)
      __SCREAMING_SNAKE_CASE   :str						=  []
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  []
      __SCREAMING_SNAKE_CASE   :Tuple						=  []
      __SCREAMING_SNAKE_CASE   :Any						=  []
      __SCREAMING_SNAKE_CASE   :Dict						=  []
      __SCREAMING_SNAKE_CASE   :Any						=  []

      __SCREAMING_SNAKE_CASE   :List[Any]						=  []
      __SCREAMING_SNAKE_CASE   :int						=  []
      __SCREAMING_SNAKE_CASE   :str						=  []
      __SCREAMING_SNAKE_CASE   :int						=  []
      for rsent in rsents:
            __SCREAMING_SNAKE_CASE   :List[Any]						=  rsent.split(''' '''							)
            __SCREAMING_SNAKE_CASE   :str						=  []
            __SCREAMING_SNAKE_CASE   :Dict						=  []
            __SCREAMING_SNAKE_CASE   :List[Any]						=  []
            ragramslist.append(a_							)
            for i in range(0 ,   len(a_							) - 1							):
                  if i < len(a_							) - 1:
                        __SCREAMING_SNAKE_CASE   :Optional[Any]						=  ragrams[i] + ''' ''' + ragrams[i + 1]
                        ragrams.append(a_							)
                  if i < len(a_							) - 2:
                        __SCREAMING_SNAKE_CASE   :Any						=  ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2]
                        ragrams.append(a_							)
                  if i < len(a_							) - 3:
                        __SCREAMING_SNAKE_CASE   :Optional[int]						=  ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2] + ''' ''' + ragrams[i + 3]
                        ragrams.append(a_							)
            ragramslist.append(a_							)
            ragramslist.append(a_							)
            ragramslist.append(a_							)

      for i in range(0 ,   len(a_							) - 1							):
            if i < len(a_							) - 1:
                  __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  sagrams[i] + ''' ''' + sagrams[i + 1]
                  sagrams.append(a_							)
            if i < len(a_							) - 2:
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2]
                  sagrams.append(a_							)
            if i < len(a_							) - 3:
                  __SCREAMING_SNAKE_CASE   :List[Any]						=  sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2] + ''' ''' + sagrams[i + 3]
                  sagrams.append(a_							)

      for i in range(0 ,   len(a_							) - 1							):
            if i < len(a_							) - 1:
                  __SCREAMING_SNAKE_CASE   :Any						=  cagrams[i] + ''' ''' + cagrams[i + 1]
                  cagrams.append(a_							)
            if i < len(a_							) - 2:
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2]
                  cagrams.append(a_							)
            if i < len(a_							) - 3:
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2] + ''' ''' + cagrams[i + 3]
                  cagrams.append(a_							)

      ((__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE))   :Optional[Any]						=  SARIngram(a_ ,   a_ ,   a_ ,   a_							)
      ((__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE))   :Union[str, Any]						=  SARIngram(a_ ,   a_ ,   a_ ,   a_							)
      ((__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE))   :Union[str, Any]						=  SARIngram(a_ ,   a_ ,   a_ ,   a_							)
      ((__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE)				,(__SCREAMING_SNAKE_CASE))   :Any						=  SARIngram(a_ ,   a_ ,   a_ ,   a_							)
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  sum([keepascore, keepascore, keepascore, keepascore]							) / 4
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  sum([delascore, delascore, delascore, delascore]							) / 4
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  sum([addascore, addascore, addascore, addascore]							) / 4
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  (avgkeepscore + avgdelscore + avgaddscore) / 3
      return finalscore



def      __lowerCamelCase   (							a_     :		Dict ,   a_     :		bool = True ,   a_     :		str = "13a" ,   a_     :		bool = True							)			->      Any:
      # Normalization is requried for the ASSET dataset (one of the primary
      # datasets in sentence simplification) to allow using space
      # to split the sentence. Even though Wiki-Auto and TURK datasets,
      # do not require normalization, we do it for consistency.
      # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset.
      # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7

      if lowercase:
            __SCREAMING_SNAKE_CASE   :Tuple						=  sentence.lower()

      if tokenizer in ["13a", "intl"]:
            if version.parse(sacrebleu.__version__							).major >= 2:
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  sacrebleu.metrics.bleu._get_tokenizer(a_							)()(a_							)
            else:
                  __SCREAMING_SNAKE_CASE   :Optional[int]						=  sacrebleu.TOKENIZERS[tokenizer]()(a_							)
      elif tokenizer == "moses":
            __SCREAMING_SNAKE_CASE   :str						=  sacremoses.MosesTokenizer().tokenize(a_ ,   return_str=a_ ,   escape=a_							)
      elif tokenizer == "penn":
            __SCREAMING_SNAKE_CASE   :List[str]						=  sacremoses.MosesTokenizer().penn_tokenize(a_ ,   return_str=a_							)
      else:
            __SCREAMING_SNAKE_CASE   :Dict						=  sentence

      if not return_str:
            __SCREAMING_SNAKE_CASE   :int						=  normalized_sent.split()

      return normalized_sent



def      __lowerCamelCase   (							a_     :		Tuple ,   a_     :		str ,   a_     :		List[Any]							)			->      Tuple:
      if not (len(a_							) == len(a_							) == len(a_							)):
            raise ValueError('''Sources length must match predictions and references lengths.'''							)
      __SCREAMING_SNAKE_CASE   :Dict						=  0
      for src, pred, refs in zip(a_ ,   a_ ,   a_							):
            sari_score += SARIsent(normalize(a_							) ,   normalize(a_							) ,   [normalize(a_							) for sent in refs]							)
      __SCREAMING_SNAKE_CASE   :Any						=  sari_score / len(a_							)
      return 1_00 * sari_score



def      __lowerCamelCase   (							a_     :		Union[str, Any] ,   a_     :		Dict ,   a_     :		Dict="exp" ,   a_     :		Any=None ,   a_     :		List[str]=False ,   a_     :		List[Any]=False ,   a_     :		Optional[int]=False ,   )			->      Dict:
      __SCREAMING_SNAKE_CASE   :str						=  len(references[0]							)
      if any(len(a_							) != references_per_prediction for refs in references							):
            raise ValueError('''Sacrebleu requires the same number of references for each prediction'''							)
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  [[refs[i] for refs in references] for i in range(a_							)]
      __SCREAMING_SNAKE_CASE   :List[Any]						=  sacrebleu.corpus_bleu(
          a_ ,   a_ ,   smooth_method=a_ ,   smooth_value=a_ ,   force=a_ ,   lowercase=a_ ,   use_effective_order=a_ ,   )
      return output.score







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




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





             """simple docstring"""






             return datasets.MetricInfo(
                 description=_DESCRIPTION		,citation=_CITATION		,inputs_description=_KWARGS_DESCRIPTION		,features=datasets.Features(
                     {
                         '''predictions''': datasets.Value('''string'''		,id='''sequence'''							),
                         '''references''': datasets.Sequence(datasets.Value('''string'''		,id='''sequence'''							)		,id='''references'''							),
                     }							)		,codebase_urls=[
                     '''https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py''',
                     '''https://github.com/cocoxu/simplification/blob/master/SARI.py''',
                     '''https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py''',
                     '''https://github.com/mjpost/sacreBLEU''',
                 ]		,reference_urls=[
                     '''https://www.aclweb.org/anthology/Q16-1029.pdf''',
                     '''https://github.com/mjpost/sacreBLEU''',
                     '''https://en.wikipedia.org/wiki/BLEU''',
                     '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''',
                 ]		,)




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)			->      Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Dict						=  {}
             result.update({'''sari''': compute_sari(sources=SCREAMING_SNAKE_CASE__		,predictions=SCREAMING_SNAKE_CASE__		,references=SCREAMING_SNAKE_CASE__							)}							)
             result.update({'''sacrebleu''': compute_sacrebleu(predictions=SCREAMING_SNAKE_CASE__		,references=SCREAMING_SNAKE_CASE__							)}							)
             result.update({'''exact''': compute_em(predictions=SCREAMING_SNAKE_CASE__		,references=SCREAMING_SNAKE_CASE__							)}							)
             return result






"""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(   A    ,	unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_   :      Optional[Any]							=  ConsistencyModelPipeline
       SCREAMING_SNAKE_CASE_   :      Any							=  UNCONDITIONAL_IMAGE_GENERATION_PARAMS
       SCREAMING_SNAKE_CASE_   :      Dict							=  UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

       # Override required_optional_params to remove num_images_per_prompt
       SCREAMING_SNAKE_CASE_   :      Optional[Any]							=  frozenset(
           [
               '''num_inference_steps''',
               '''generator''',
               '''latents''',
               '''output_type''',
               '''return_dict''',
               '''callback''',
               '''callback_steps''',
           ]  )




       @property
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  UNetaDModel.from_pretrained(
                 '''diffusers/consistency-models-test'''		,subfolder='''test_unet'''		,)
             return unet




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[int]						=  UNetaDModel.from_pretrained(
                 '''diffusers/consistency-models-test'''		,subfolder='''test_unet_class_cond'''		,)
             return unet




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__=False							)			->      Union[str, Any]:





             """simple docstring"""






             if class_cond:
                   __SCREAMING_SNAKE_CASE   :str						=  self.dummy_cond_unet
             else:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  self.dummy_uncond_unet

             # Default to CM multistep sampler
             __SCREAMING_SNAKE_CASE   :List[str]						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)

             __SCREAMING_SNAKE_CASE   :List[str]						=  {
                 '''unet''': unet,
                 '''scheduler''': scheduler,
             }

             return components




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=0							)			->      Dict:





             """simple docstring"""






             if str(SCREAMING_SNAKE_CASE__							).startswith('''mps'''							):
                   __SCREAMING_SNAKE_CASE   :Tuple						=  torch.manual_seed(SCREAMING_SNAKE_CASE__							)
             else:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  torch.Generator(device=SCREAMING_SNAKE_CASE__							).manual_seed(SCREAMING_SNAKE_CASE__							)

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

             return inputs




       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :List[str]						=  self.get_dummy_components()
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :List[str]						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :Any						=  np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]							)

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




       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :List[Any]						=  self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  0
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :Dict						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :List[Any]						=  np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]							)

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




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[str]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :Tuple						=  self.get_dummy_components()
             __SCREAMING_SNAKE_CASE   :Any						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Dict						=  1
             __SCREAMING_SNAKE_CASE   :List[str]						=  None
             __SCREAMING_SNAKE_CASE   :List[str]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :List[str]						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :int						=  np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]							)

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




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :Any						=  self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Dict						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  1
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  None
             __SCREAMING_SNAKE_CASE   :List[Any]						=  0
             __SCREAMING_SNAKE_CASE   :Any						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :int						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]							)

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






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




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





             """simple docstring"""






             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__="cpu"		,SCREAMING_SNAKE_CASE__=torch.floataa		,SCREAMING_SNAKE_CASE__=(1, 3, 64, 64)							)			->      Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  torch.manual_seed(SCREAMING_SNAKE_CASE__							)

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

             if get_fixed_latents:
                   __SCREAMING_SNAKE_CASE   :int						=  self.get_fixed_latents(seed=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__		,dtype=SCREAMING_SNAKE_CASE__		,shape=SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE   :int						=  latents

             return inputs




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__="cpu"		,SCREAMING_SNAKE_CASE__=torch.floataa		,SCREAMING_SNAKE_CASE__=(1, 3, 64, 64)							)			->      int:





             """simple docstring"""






             if type(SCREAMING_SNAKE_CASE__							) == str:
                   __SCREAMING_SNAKE_CASE   :int						=  torch.device(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  torch.Generator(device=SCREAMING_SNAKE_CASE__							).manual_seed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  randn_tensor(SCREAMING_SNAKE_CASE__		,generator=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__		,dtype=SCREAMING_SNAKE_CASE__							)
             return latents




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :Dict						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :int						=  self.get_inputs()
             __SCREAMING_SNAKE_CASE   :List[str]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 64, 64, 3)

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :Dict						=  np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4]							)

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




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :List[Any]						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :Any						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  self.get_inputs()
             __SCREAMING_SNAKE_CASE   :int						=  1
             __SCREAMING_SNAKE_CASE   :int						=  None
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 64, 64, 3)

             __SCREAMING_SNAKE_CASE   :str						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :List[str]						=  np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7]							)

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




       @require_torch_a
       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :Any						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :Any						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__		,torch_dtype=torch.floataa							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__							)
             # Ensure usage of flash attention in torch 2.0
             with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__		,enable_math=SCREAMING_SNAKE_CASE__		,enable_mem_efficient=SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 64, 64, 3)

             __SCREAMING_SNAKE_CASE   :List[str]						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :List[Any]						=  np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3]							)

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




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :Dict						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :int						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__		,torch_dtype=torch.floataa							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

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

             __SCREAMING_SNAKE_CASE   :str						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5]							)

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