





import re
import string
from collections import Counter

import sacrebleu
import sacremoses
from packaging import version

import datasets


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

_lowerCAmelCase 				=     """\
WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU
It can be used to evaluate the quality of machine-generated texts.
"""


_lowerCAmelCase 				=     """
Calculates sari score (between 0 and 100) given a list of source and predicted
sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.
Args:
    sources: list of source sentences where each sentence should be a string.
    predictions: list of predicted sentences where each sentence should be a string.
    references: list of lists of reference sentences where each sentence should be a string.
Returns:
    sari: sari score
    sacrebleu: sacrebleu score
    exact: exact score

Examples:
    >>> sources=[\"About 95 species are currently accepted .\"]
    >>> predictions=[\"About 95 you now get in .\"]
    >>> references=[[\"About 95 species are currently known .\"]]
    >>> wiki_split = datasets.load_metric(\"wiki_split\")
    >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)
    >>> print(results)
    {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0}
"""



def     _lowerCAmelCase		(  _lowerCAmelCase     ):
   '''simple docstring'''


   def remove_articles(_lowerCAmelCase     ):
      A_     :				int			      =	re.compile(r"""\b(a|an|the)\b"""  ,re.UNICODE     )
      return re.sub(_lowerCAmelCase  ,""" """  ,_lowerCAmelCase     )

   def white_space_fix(_lowerCAmelCase     ):
      return " ".join(text.split()     )

   def remove_punc(_lowerCAmelCase     ):
      A_     :				Optional[Any]			      =	set(string.punctuation     )
      return "".join(ch for ch in text if ch not in exclude     )

   def lower(_lowerCAmelCase     ):
      return text.lower()

   return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase     )     )     )     )



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase     ):
   '''simple docstring'''


   return int(normalize_answer(_lowerCAmelCase     ) == normalize_answer(_lowerCAmelCase     )     )



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase     ):
   '''simple docstring'''


   A_     :				Tuple			      =	[any(compute_exact(_lowerCAmelCase  ,_lowerCAmelCase     ) for ref in refs     ) for pred, refs in zip(_lowerCAmelCase  ,_lowerCAmelCase     )]
   return (sum(_lowerCAmelCase     ) / len(_lowerCAmelCase     )) * 1_0_0



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     ):
   '''simple docstring'''


   A_     :				Tuple			      =	[rgram for rgrams in rgramslist for rgram in rgrams]
   A_     :				List[Any]			      =	Counter(_lowerCAmelCase     )

   A_     :				Optional[Any]			      =	Counter(_lowerCAmelCase     )
   A_     :				Tuple			      =	Counter()
   for sgram, scount in sgramcounter.items():
      A_     :				Optional[int]			      =	scount * numref

   A_     :				Union[str, Any]			      =	Counter(_lowerCAmelCase     )
   A_     :				Dict			      =	Counter()
   for cgram, ccount in cgramcounter.items():
      A_     :				int			      =	ccount * numref

   # KEEP
   A_     :				Tuple			      =	sgramcounter_rep & cgramcounter_rep
   A_     :				List[Any]			      =	keepgramcounter_rep & rgramcounter
   A_     :				Union[str, Any]			      =	sgramcounter_rep & rgramcounter

   A_     :				int			      =	0
   A_     :				int			      =	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.
   A_     :				List[str]			      =	1
   A_     :				Optional[int]			      =	1
   if len(_lowerCAmelCase     ) > 0:
      A_     :				Optional[int]			      =	keeptmpscorea / len(_lowerCAmelCase     )
   if len(_lowerCAmelCase     ) > 0:
      # Fix an alleged bug [2] in the keep score computation.
      # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
      A_     :				List[Any]			      =	keeptmpscorea / sum(keepgramcounterall_rep.values()     )
   A_     :				List[Any]			      =	0
   if keepscore_precision > 0 or keepscore_recall > 0:
      A_     :				Tuple			      =	2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)

   # DELETION
   A_     :				Any			      =	sgramcounter_rep - cgramcounter_rep
   A_     :				Union[str, Any]			      =	delgramcounter_rep - rgramcounter
   A_     :				int			      =	sgramcounter_rep - rgramcounter
   A_     :				List[str]			      =	0
   A_     :				Union[str, Any]			      =	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.
   A_     :				List[str]			      =	1
   if len(_lowerCAmelCase     ) > 0:
      A_     :				Optional[Any]			      =	deltmpscorea / len(_lowerCAmelCase     )

   # ADDITION
   A_     :				int			      =	set(_lowerCAmelCase     ) - set(_lowerCAmelCase     )
   A_     :				List[str]			      =	set(_lowerCAmelCase     ) & set(_lowerCAmelCase     )
   A_     :				List[Any]			      =	set(_lowerCAmelCase     ) - set(_lowerCAmelCase     )

   A_     :				Dict			      =	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.
   A_     :				List[str]			      =	1
   A_     :				Optional[int]			      =	1
   if len(_lowerCAmelCase     ) > 0:
      A_     :				Optional[int]			      =	addtmpscore / len(_lowerCAmelCase     )
   if len(_lowerCAmelCase     ) > 0:
      A_     :				Dict			      =	addtmpscore / len(_lowerCAmelCase     )
   A_     :				Any			      =	0
   if addscore_precision > 0 or addscore_recall > 0:
      A_     :				Optional[int]			      =	2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)

   return (keepscore, delscore_precision, addscore)



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     ):
   '''simple docstring'''


   A_     :				Dict			      =	len(_lowerCAmelCase     )

   A_     :				Optional[Any]			      =	ssent.split(""" """     )
   A_     :				int			      =	csent.split(""" """     )
   A_     :				Any			      =	[]
   A_     :				Optional[Any]			      =	[]
   A_     :				List[str]			      =	[]
   A_     :				int			      =	[]
   A_     :				List[Any]			      =	[]
   A_     :				Optional[Any]			      =	[]

   A_     :				Optional[int]			      =	[]
   A_     :				List[Any]			      =	[]
   A_     :				Union[str, Any]			      =	[]
   A_     :				str			      =	[]
   for rsent in rsents:
      A_     :				List[str]			      =	rsent.split(""" """     )
      A_     :				Any			      =	[]
      A_     :				List[str]			      =	[]
      A_     :				str			      =	[]
      ragramslist.append(_lowerCAmelCase     )
      for i in range(0  ,len(_lowerCAmelCase     ) - 1     ):
         if i < len(_lowerCAmelCase     ) - 1:
            A_     :				str			      =	ragrams[i] + """ """ + ragrams[i + 1]
            ragrams.append(_lowerCAmelCase     )
         if i < len(_lowerCAmelCase     ) - 2:
            A_     :				Tuple			      =	ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2]
            ragrams.append(_lowerCAmelCase     )
         if i < len(_lowerCAmelCase     ) - 3:
            A_     :				int			      =	ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] + """ """ + ragrams[i + 3]
            ragrams.append(_lowerCAmelCase     )
      ragramslist.append(_lowerCAmelCase     )
      ragramslist.append(_lowerCAmelCase     )
      ragramslist.append(_lowerCAmelCase     )

   for i in range(0  ,len(_lowerCAmelCase     ) - 1     ):
      if i < len(_lowerCAmelCase     ) - 1:
         A_     :				str			      =	sagrams[i] + """ """ + sagrams[i + 1]
         sagrams.append(_lowerCAmelCase     )
      if i < len(_lowerCAmelCase     ) - 2:
         A_     :				List[Any]			      =	sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2]
         sagrams.append(_lowerCAmelCase     )
      if i < len(_lowerCAmelCase     ) - 3:
         A_     :				List[Any]			      =	sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] + """ """ + sagrams[i + 3]
         sagrams.append(_lowerCAmelCase     )

   for i in range(0  ,len(_lowerCAmelCase     ) - 1     ):
      if i < len(_lowerCAmelCase     ) - 1:
         A_     :				Union[str, Any]			      =	cagrams[i] + """ """ + cagrams[i + 1]
         cagrams.append(_lowerCAmelCase     )
      if i < len(_lowerCAmelCase     ) - 2:
         A_     :				str			      =	cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2]
         cagrams.append(_lowerCAmelCase     )
      if i < len(_lowerCAmelCase     ) - 3:
         A_     :				List[str]			      =	cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] + """ """ + cagrams[i + 3]
         cagrams.append(_lowerCAmelCase     )

   ((A_)      ,				(A_)      ,				(A_))     :				str			      =	SARIngram(_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     )
   ((A_)      ,				(A_)      ,				(A_))     :				Dict			      =	SARIngram(_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     )
   ((A_)      ,				(A_)      ,				(A_))     :				List[Any]			      =	SARIngram(_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     )
   ((A_)      ,				(A_)      ,				(A_))     :				List[str]			      =	SARIngram(_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     )
   A_     :				List[str]			      =	sum([keepascore, keepascore, keepascore, keepascore]     ) / 4
   A_     :				Optional[int]			      =	sum([delascore, delascore, delascore, delascore]     ) / 4
   A_     :				Tuple			      =	sum([addascore, addascore, addascore, addascore]     ) / 4
   A_     :				List[Any]			      =	(avgkeepscore + avgdelscore + avgaddscore) / 3
   return finalscore



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase = True  ,_lowerCAmelCase = "13a"  ,_lowerCAmelCase = True     ):
   '''simple docstring'''


   if lowercase:
      A_     :				List[str]			      =	sentence.lower()

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

   if not return_str:
      A_     :				List[str]			      =	normalized_sent.split()

   return normalized_sent



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     ):
   '''simple docstring'''


   if not (len(_lowerCAmelCase     ) == len(_lowerCAmelCase     ) == len(_lowerCAmelCase     )):
      raise ValueError("""Sources length must match predictions and references lengths."""     )
   A_     :				Optional[Any]			      =	0
   for src, pred, refs in zip(_lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase     ):
      sari_score += SARIsent(normalize(_lowerCAmelCase     )  ,normalize(_lowerCAmelCase     )  ,[normalize(_lowerCAmelCase     ) for sent in refs]     )
   A_     :				List[str]			      =	sari_score / len(_lowerCAmelCase     )
   return 1_0_0 * sari_score



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase="exp"  ,_lowerCAmelCase=None  ,_lowerCAmelCase=False  ,_lowerCAmelCase=False  ,_lowerCAmelCase=False  ,):
   '''simple docstring'''


   A_     :				int			      =	len(references[0]     )
   if any(len(_lowerCAmelCase     ) != references_per_prediction for refs in references     ):
      raise ValueError("""Sacrebleu requires the same number of references for each prediction"""     )
   A_     :				List[Any]			      =	[[refs[i] for refs in references] for i in range(_lowerCAmelCase     )]
   A_     :				List[str]			      =	sacrebleu.corpus_bleu(
       _lowerCAmelCase  ,_lowerCAmelCase  ,smooth_method=_lowerCAmelCase  ,smooth_value=_lowerCAmelCase  ,force=_lowerCAmelCase  ,lowercase=_lowerCAmelCase  ,use_effective_order=_lowerCAmelCase  ,)
   return output.score







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,       _KWARGS_DESCRIPTION     )
class    _UpperCAmelCase							(		datasets.Metric     ):
      def 		_lowerCamelCase      (		self       ):
         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 		_lowerCamelCase      (		self      ,       a__      ,       a__      ,       a__       ):
         A_     :				List[Any]			      =	{}
         result.update({"""sari""": compute_sari(sources=a__      ,       predictions=a__      ,       references=a__       )}       )
         result.update({"""sacrebleu""": compute_sacrebleu(predictions=a__      ,       references=a__       )}       )
         result.update({"""exact""": compute_em(predictions=a__      ,       references=a__       )}       )
         return result













import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class    _UpperCAmelCase							(		_lowerCamelCase			,       _lowerCamelCase			,       _lowerCamelCase			,       unittest.TestCase     ):
      a						       =							AltDiffusionPipeline
      a						       =							TEXT_TO_IMAGE_PARAMS
      a						       =							TEXT_TO_IMAGE_BATCH_PARAMS
      a						       =							TEXT_TO_IMAGE_IMAGE_PARAMS
      a						       =							TEXT_TO_IMAGE_IMAGE_PARAMS
      def 		_lowerCamelCase      (		self       ):
         torch.manual_seed(0       )
         A_     :				Optional[int]			      =	UNetaDConditionModel(
             block_out_channels=(32, 64)      ,       layers_per_block=2      ,       sample_size=32      ,       in_channels=4      ,       out_channels=4      ,       down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")      ,       up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")      ,       cross_attention_dim=32      ,       )
         A_     :				List[Any]			      =	DDIMScheduler(
             beta_start=0.0_0085      ,       beta_end=0.012      ,       beta_schedule="""scaled_linear"""      ,       clip_sample=a__      ,       set_alpha_to_one=a__      ,       )
         torch.manual_seed(0       )
         A_     :				int			      =	AutoencoderKL(
             block_out_channels=[32, 64]      ,       in_channels=3      ,       out_channels=3      ,       down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]      ,       up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]      ,       latent_channels=4      ,       )

         # TODO: address the non-deterministic text encoder (fails for save-load tests)
         # torch.manual_seed(0)
         # text_encoder_config = RobertaSeriesConfig(
         #     hidden_size=32,
         #     project_dim=32,
         #     intermediate_size=37,
         #     layer_norm_eps=1e-05,
         #     num_attention_heads=4,
         #     num_hidden_layers=5,
         #     vocab_size=5002,
         # )
         # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

         torch.manual_seed(0       )
         A_     :				Optional[int]			      =	CLIPTextConfig(
             bos_token_id=0      ,       eos_token_id=2      ,       hidden_size=32      ,       projection_dim=32      ,       intermediate_size=37      ,       layer_norm_eps=1E-05      ,       num_attention_heads=4      ,       num_hidden_layers=5      ,       pad_token_id=1      ,       vocab_size=5002      ,       )
         A_     :				Optional[Any]			      =	CLIPTextModel(a__       )

         A_     :				Union[str, Any]			      =	XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""       )
         A_     :				str			      =	77

         A_     :				Optional[Any]			      =	{
             """unet""": unet,
             """scheduler""": scheduler,
             """vae""": vae,
             """text_encoder""": text_encoder,
             """tokenizer""": tokenizer,
             """safety_checker""": None,
             """feature_extractor""": None,
         }
         return components
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__=0       ):
         if str(a__       ).startswith("""mps"""       ):
            A_     :				Union[str, Any]			      =	torch.manual_seed(a__       )
         else:
            A_     :				Dict			      =	torch.Generator(device=a__       ).manual_seed(a__       )
         A_     :				Dict			      =	{
             """prompt""": """A painting of a squirrel eating a burger""",
             """generator""": generator,
             """num_inference_steps""": 2,
             """guidance_scale""": 6.0,
             """output_type""": """numpy""",
         }
         return inputs
      def 		_lowerCamelCase      (		self       ):
         super().test_attention_slicing_forward_pass(expected_max_diff=3E-3       )
      def 		_lowerCamelCase      (		self       ):
         super().test_inference_batch_single_identical(expected_max_diff=3E-3       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				Optional[Any]			      =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator

         A_     :				Union[str, Any]			      =	self.get_dummy_components()
         torch.manual_seed(0       )
         A_     :				List[str]			      =	RobertaSeriesConfig(
             hidden_size=32      ,       project_dim=32      ,       intermediate_size=37      ,       layer_norm_eps=1E-05      ,       num_attention_heads=4      ,       num_hidden_layers=5      ,       vocab_size=5002      ,       )
         # TODO: remove after fixing the non-deterministic text encoder
         A_     :				Dict			      =	RobertaSeriesModelWithTransformation(a__       )
         A_     :				Any			      =	text_encoder

         A_     :				Tuple			      =	AltDiffusionPipeline(**a__       )
         A_     :				int			      =	alt_pipe.to(a__       )
         alt_pipe.set_progress_bar_config(disable=a__       )

         A_     :				Union[str, Any]			      =	self.get_dummy_inputs(a__       )
         A_     :				Tuple			      =	"""A photo of an astronaut"""
         A_     :				Dict			      =	alt_pipe(**a__       )
         A_     :				List[str]			      =	output.images
         A_     :				List[Any]			      =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         A_     :				Tuple			      =	np.array(
             [0.574_8162, 0.6044_7145, 0.4882_1217, 0.5010_0636, 0.543_1185, 0.4576_3683, 0.4965_7696, 0.4813_2733, 0.4757_3093]       )

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






      def 		_lowerCamelCase      (		self       ):
         A_     :				Tuple			      =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator

         A_     :				Union[str, Any]			      =	self.get_dummy_components()
         A_     :				str			      =	PNDMScheduler(skip_prk_steps=a__       )
         torch.manual_seed(0       )
         A_     :				Any			      =	RobertaSeriesConfig(
             hidden_size=32      ,       project_dim=32      ,       intermediate_size=37      ,       layer_norm_eps=1E-05      ,       num_attention_heads=4      ,       num_hidden_layers=5      ,       vocab_size=5002      ,       )
         # TODO: remove after fixing the non-deterministic text encoder
         A_     :				int			      =	RobertaSeriesModelWithTransformation(a__       )
         A_     :				Any			      =	text_encoder
         A_     :				Any			      =	AltDiffusionPipeline(**a__       )
         A_     :				int			      =	alt_pipe.to(a__       )
         alt_pipe.set_progress_bar_config(disable=a__       )

         A_     :				Union[str, Any]			      =	self.get_dummy_inputs(a__       )
         A_     :				Union[str, Any]			      =	alt_pipe(**a__       )
         A_     :				List[str]			      =	output.images
         A_     :				List[Any]			      =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         A_     :				List[Any]			      =	np.array(
             [0.5160_5093, 0.570_7241, 0.4736_5507, 0.5057_8886, 0.563_3877, 0.464_2503, 0.518_2081, 0.4876_3484, 0.4908_4237]       )

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






@slow
@require_torch_gpu
class    _UpperCAmelCase							(		unittest.TestCase     ):
      def 		_lowerCamelCase      (		self       ):
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()
      def 		_lowerCamelCase      (		self       ):
         # make sure here that pndm scheduler skips prk
         A_     :				Any			      =	AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion"""      ,       safety_checker=a__       )
         A_     :				Optional[int]			      =	alt_pipe.to(a__       )
         alt_pipe.set_progress_bar_config(disable=a__       )

         A_     :				Tuple			      =	"""A painting of a squirrel eating a burger"""
         A_     :				Tuple			      =	torch.manual_seed(0       )
         A_     :				int			      =	alt_pipe([prompt]      ,       generator=a__      ,       guidance_scale=6.0      ,       num_inference_steps=20      ,       output_type="""np"""       )

         A_     :				Optional[Any]			      =	output.images

         A_     :				int			      =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         A_     :				str			      =	np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586]       )

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






      def 		_lowerCamelCase      (		self       ):
         A_     :				Dict			      =	DDIMScheduler.from_pretrained("""BAAI/AltDiffusion"""      ,       subfolder="""scheduler"""       )

         A_     :				int			      =	AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion"""      ,       scheduler=a__      ,       safety_checker=a__       )
         A_     :				Dict			      =	alt_pipe.to(a__       )
         alt_pipe.set_progress_bar_config(disable=a__       )

         A_     :				Optional[int]			      =	"""A painting of a squirrel eating a burger"""
         A_     :				Any			      =	torch.manual_seed(0       )

         A_     :				List[str]			      =	alt_pipe([prompt]      ,       generator=a__      ,       num_inference_steps=2      ,       output_type="""numpy"""       )
         A_     :				List[Any]			      =	output.images

         A_     :				Tuple			      =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         A_     :				Any			      =	np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323]       )

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






