




"""simple docstring"""





import argparse
import ast
import logging
import os
import sys

import pandas as pd
import torch
from tqdm import tqdm

from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score  # noqa: E402 # isort:skip


_lowercase						   =     logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()

def 		lowerCAmelCase				(			lowerCamelCase		):
						'''simple docstring'''


						if "token" in model_name_or_path:
												return "rag_token"
						if "sequence" in model_name_or_path:
												return "rag_sequence"
						if "bart" in model_name_or_path:
												return "bart"
						return None

def 		lowerCAmelCase				(			lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		):
						'''simple docstring'''


						return max(metric_fn(lowerCamelCase   ,      lowerCamelCase		) for gt in ground_truths		)

def 		lowerCAmelCase				(			lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		):
						'''simple docstring'''


						snake_case__							:       str				      =       [line.strip() for line in open(lowerCamelCase   ,      '''r'''		).readlines()]
						snake_case__							:       List[Any]				      =       []

						if args.gold_data_mode == "qa":
												snake_case__							:       Any				      =       pd.read_csv(lowerCamelCase   ,      sep='''\t'''   ,      header=lowerCamelCase		)
												for answer_list in data[1]:
																		snake_case__							:       List[str]				      =       ast.literal_eval(lowerCamelCase		)
																		answers.append(lowerCamelCase		)
						else:
												snake_case__							:       Tuple				      =       [line.strip() for line in open(lowerCamelCase   ,      '''r'''		).readlines()]
												snake_case__							:       List[str]				      =       [[reference] for reference in references]

						snake_case__							:       Dict				      =       0
						for prediction, ground_truths in zip(lowerCamelCase   ,      lowerCamelCase		):
												total += 1
												em += metric_max_over_ground_truths(lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		)
												fa += metric_max_over_ground_truths(lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		)

						snake_case__							:       Union[str, Any]				      =       100.0 * em / total
						snake_case__							:       Union[str, Any]				      =       100.0 * fa / total

						logger.info(f'''F1: {fa:.2f}'''		)
						logger.info(f'''EM: {em:.2f}'''		)

def 		lowerCAmelCase				(			lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		):
						'''simple docstring'''


						snake_case__							:       str				      =       args.k
						snake_case__							:       Dict				      =       [line.strip() for line in open(lowerCamelCase   ,      '''r'''		).readlines()]
						snake_case__							:       Optional[Any]				      =       [line.strip() for line in open(lowerCamelCase   ,      '''r'''		).readlines()]

						snake_case__							:       Tuple				      =       0
						for hypo, reference in zip(lowerCamelCase   ,      lowerCamelCase		):
												snake_case__							:       List[str]				      =       set(hypo.split('''\t'''		)[:k]		)
												snake_case__							:       Union[str, Any]				      =       set(reference.split('''\t'''		)		)
												total += 1
												em += len(hypo_provenance & ref_provenance		) / k

						snake_case__							:       List[Any]				      =       100.0 * em / total
						logger.info(f'''Precision@{k}: {em: .2f}'''		)

def 		lowerCAmelCase				(			lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		):
						'''simple docstring'''


						def strip_title(lowerCamelCase		):
												if title.startswith('''"'''		):
																		snake_case__							:       Optional[Any]				      =       title[1:]
												if title.endswith('''"'''		):
																		snake_case__							:       Optional[Any]				      =       title[:-1]
												return title

						snake_case__							:       Any				      =       rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
						    lowerCamelCase   ,      return_tensors='''pt'''   ,      padding=lowerCamelCase   ,      truncation=lowerCamelCase   ,      )['''input_ids'''].to(args.device		)

						snake_case__							:       str				      =       rag_model.rag.question_encoder(lowerCamelCase		)
						snake_case__							:       str				      =       question_enc_outputs[0]

						snake_case__							:       Tuple				      =       rag_model.retriever(
						    lowerCamelCase   ,      question_enc_pool_output.cpu().detach().to(torch.floataa		).numpy()   ,      prefix=rag_model.rag.generator.config.prefix   ,      n_docs=rag_model.config.n_docs   ,      return_tensors='''pt'''   ,      )
						snake_case__							:       Tuple				      =       rag_model.retriever.index.get_doc_dicts(result.doc_ids		)
						snake_case__							:       Optional[int]				      =       []
						for docs in all_docs:
												snake_case__							:       Optional[int]				      =       [strip_title(lowerCamelCase		) for title in docs['''title''']]
												provenance_strings.append('''\t'''.join(lowerCamelCase		)		)
						return provenance_strings

def 		lowerCAmelCase				(			lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		):
						'''simple docstring'''


						with torch.no_grad():
												snake_case__							:       Tuple				      =       rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
												    lowerCamelCase   ,      return_tensors='''pt'''   ,      padding=lowerCamelCase   ,      truncation=lowerCamelCase		)

												snake_case__							:       Dict				      =       inputs_dict.input_ids.to(args.device		)
												snake_case__							:       int				      =       inputs_dict.attention_mask.to(args.device		)
												snake_case__							:       Optional[int]				      =       rag_model.generate(  # rag_model overwrites generate
												    lowerCamelCase   ,      attention_mask=lowerCamelCase   ,      num_beams=args.num_beams   ,      min_length=args.min_length   ,      max_length=args.max_length   ,      early_stopping=lowerCamelCase   ,      num_return_sequences=1   ,      bad_words_ids=[[0, 0]]   ,      )
												snake_case__							:       int				      =       rag_model.retriever.generator_tokenizer.batch_decode(lowerCamelCase   ,      skip_special_tokens=lowerCamelCase		)

												if args.print_predictions:
																		for q, a in zip(lowerCamelCase   ,      lowerCamelCase		):
																								logger.info('''Q: {} - A: {}'''.format(lowerCamelCase   ,      lowerCamelCase		)		)

												return answers

def 		lowerCAmelCase				(			):
						'''simple docstring'''


						snake_case__							:       Optional[int]				      =       argparse.ArgumentParser()
						parser.add_argument(
						    '''--model_type'''   ,      choices=['''rag_sequence''', '''rag_token''', '''bart''']   ,      type=lowerCamelCase   ,      help=(
						        '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the'''
						        ''' model_name_or_path'''
						    )   ,      )
						parser.add_argument(
						    '''--index_name'''   ,      default=lowerCamelCase   ,      choices=['''exact''', '''compressed''', '''legacy''']   ,      type=lowerCamelCase   ,      help='''RAG model retriever type'''   ,      )
						parser.add_argument(
						    '''--index_path'''   ,      default=lowerCamelCase   ,      type=lowerCamelCase   ,      help='''Path to the retrieval index'''   ,      )
						parser.add_argument('''--n_docs'''   ,      default=5   ,      type=lowerCamelCase   ,      help='''Number of retrieved docs'''		)
						parser.add_argument(
						    '''--model_name_or_path'''   ,      default=lowerCamelCase   ,      type=lowerCamelCase   ,      required=lowerCamelCase   ,      help='''Path to pretrained checkpoints or model identifier from huggingface.co/models'''   ,      )
						parser.add_argument(
						    '''--eval_mode'''   ,      choices=['''e2e''', '''retrieval''']   ,      default='''e2e'''   ,      type=lowerCamelCase   ,      help=(
						        '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates'''
						        ''' precision@k.'''
						    )   ,      )
						parser.add_argument('''--k'''   ,      default=1   ,      type=lowerCamelCase   ,      help='''k for the precision@k calculation'''		)
						parser.add_argument(
						    '''--evaluation_set'''   ,      default=lowerCamelCase   ,      type=lowerCamelCase   ,      required=lowerCamelCase   ,      help='''Path to a file containing evaluation samples'''   ,      )
						parser.add_argument(
						    '''--gold_data_path'''   ,      default=lowerCamelCase   ,      type=lowerCamelCase   ,      required=lowerCamelCase   ,      help='''Path to a tab-separated file with gold samples'''   ,      )
						parser.add_argument(
						    '''--gold_data_mode'''   ,      default='''qa'''   ,      type=lowerCamelCase   ,      choices=['''qa''', '''ans''']   ,      help=(
						        '''Format of the gold data file'''
						        '''qa - a single line in the following format: question [tab] answer_list'''
						        '''ans - a single line of the gold file contains the expected answer string'''
						    )   ,      )
						parser.add_argument(
						    '''--predictions_path'''   ,      type=lowerCamelCase   ,      default='''predictions.txt'''   ,      help='''Name of the predictions file, to be stored in the checkpoints directory'''   ,      )
						parser.add_argument(
						    '''--eval_all_checkpoints'''   ,      action='''store_true'''   ,      help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number'''   ,      )
						parser.add_argument(
						    '''--eval_batch_size'''   ,      default=8   ,      type=lowerCamelCase   ,      help='''Batch size per GPU/CPU for evaluation.'''   ,      )
						parser.add_argument(
						    '''--recalculate'''   ,      help='''Recalculate predictions even if the prediction file exists'''   ,      action='''store_true'''   ,      )
						parser.add_argument(
						    '''--num_beams'''   ,      default=4   ,      type=lowerCamelCase   ,      help='''Number of beams to be used when generating answers'''   ,      )
						parser.add_argument('''--min_length'''   ,      default=1   ,      type=lowerCamelCase   ,      help='''Min length of the generated answers'''		)
						parser.add_argument('''--max_length'''   ,      default=50   ,      type=lowerCamelCase   ,      help='''Max length of the generated answers'''		)

						parser.add_argument(
						    '''--print_predictions'''   ,      action='''store_true'''   ,      help='''If True, prints predictions while evaluating.'''   ,      )
						parser.add_argument(
						    '''--print_docs'''   ,      action='''store_true'''   ,      help='''If True, prints docs retried while generating.'''   ,      )
						snake_case__							:       Dict				      =       parser.parse_args()
						snake_case__							:       int				      =       torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''		)
						return args

def 		lowerCAmelCase				(			lowerCamelCase		):
						'''simple docstring'''


						snake_case__							:       Tuple				      =       {}
						if args.model_type is None:
												snake_case__							:       str				      =       infer_model_type(args.model_name_or_path		)
												assert args.model_type is not None
						if args.model_type.startswith('''rag'''		):
												snake_case__							:       Union[str, Any]				      =       RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration
												snake_case__							:       List[Any]				      =       args.n_docs
												if args.index_name is not None:
																		snake_case__							:       Optional[int]				      =       args.index_name
												if args.index_path is not None:
																		snake_case__							:       Dict				      =       args.index_path
						else:
												snake_case__							:       str				      =       BartForConditionalGeneration

						snake_case__							:       int				      =       (
						    [f.path for f in os.scandir(args.model_name_or_path		) if f.is_dir()]
						    if args.eval_all_checkpoints
						    else [args.model_name_or_path]
						)

						logger.info('''Evaluate the following checkpoints: %s'''   ,      lowerCamelCase		)

						snake_case__							:       Optional[int]				      =       get_scores if args.eval_mode == '''e2e''' else get_precision_at_k
						snake_case__							:       Optional[Any]				      =       evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval

						for checkpoint in checkpoints:
												if os.path.exists(args.predictions_path		) and (not args.recalculate):
																		logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path		)		)
																		score_fn(lowerCamelCase   ,      args.predictions_path   ,      args.gold_data_path		)
																		continue

												logger.info('''***** Running evaluation for {} *****'''.format(lowerCamelCase		)		)
												logger.info('''  Batch size = %d'''   ,      args.eval_batch_size		)
												logger.info('''  Predictions will be stored under {}'''.format(args.predictions_path		)		)

												if args.model_type.startswith('''rag'''		):
																		snake_case__							:       Tuple				      =       RagRetriever.from_pretrained(lowerCamelCase   ,      **lowerCamelCase		)
																		snake_case__							:       Union[str, Any]				      =       model_class.from_pretrained(lowerCamelCase   ,      retriever=lowerCamelCase   ,      **lowerCamelCase		)
																		model.retriever.init_retrieval()
												else:
																		snake_case__							:       Union[str, Any]				      =       model_class.from_pretrained(lowerCamelCase   ,      **lowerCamelCase		)
												model.to(args.device		)

												with open(args.evaluation_set   ,      '''r'''		) as eval_file, open(args.predictions_path   ,      '''w'''		) as preds_file:
																		snake_case__							:       List[Any]				      =       []
																		for line in tqdm(lowerCamelCase		):
																								questions.append(line.strip()		)
																								if len(lowerCamelCase		) == args.eval_batch_size:
																														snake_case__							:       Union[str, Any]				      =       evaluate_batch_fn(lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		)
																														preds_file.write('''\n'''.join(lowerCamelCase		) + '''\n'''		)
																														preds_file.flush()
																														snake_case__							:       Optional[Any]				      =       []
																		if len(lowerCamelCase		) > 0:
																								snake_case__							:       Union[str, Any]				      =       evaluate_batch_fn(lowerCamelCase   ,      lowerCamelCase   ,      lowerCamelCase		)
																								preds_file.write('''\n'''.join(lowerCamelCase		)		)
																								preds_file.flush()

																		score_fn(lowerCamelCase   ,      args.predictions_path   ,      args.gold_data_path		)


if __name__ == "__main__":
							_lowercase						   =     get_args()
							main(args)








"""simple docstring"""





import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipeline as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

class    __lowercase							(      unittest.TestCase						):


				'''simple docstring'''


				def    _lowerCamelCase       ( self :  Tuple   ):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()

				@property
				def    _lowerCamelCase       ( self :  List[Any]   ):
										snake_case__							:       int				      =       1
										snake_case__							:       Any				      =       3
										snake_case__							:       Any				      =       (3_2, 3_2)

										snake_case__							:       int				      =       floats_tensor((batch_size, num_channels) + sizes   ,rng=random.Random(0   )   ).to(SCREAMING_SNAKE_CASE_   )
										return image

				@property
				def    _lowerCamelCase       ( self :  Optional[Any]   ):
										torch.manual_seed(0   )
										snake_case__							:       int				      =       UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4)   ,layers_per_block=2   ,sample_size=3_2   ,in_channels=4   ,out_channels=4   ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')   ,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')   ,cross_attention_dim=3_2   ,)
										return model

				@property
				def    _lowerCamelCase       ( self :  List[str]   ):
										torch.manual_seed(0   )
										snake_case__							:       int				      =       AutoencoderKL(
										    block_out_channels=[3_2, 6_4]   ,in_channels=3   ,out_channels=3   ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']   ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']   ,latent_channels=4   ,)
										return model

				@property
				def    _lowerCamelCase       ( self :  Optional[int]   ):
										torch.manual_seed(0   )
										snake_case__							:       str				      =       CLIPTextConfig(
										    bos_token_id=0   ,eos_token_id=2   ,hidden_size=3_2   ,intermediate_size=3_7   ,layer_norm_eps=1E-05   ,num_attention_heads=4   ,num_hidden_layers=5   ,pad_token_id=1   ,vocab_size=1_0_0_0   ,)
										return CLIPTextModel(SCREAMING_SNAKE_CASE_   )

				@property
				def    _lowerCamelCase       ( self :  Optional[int]   ):
										def extract(*SCREAMING_SNAKE_CASE_ :  Optional[int]   ,**SCREAMING_SNAKE_CASE_ :  Optional[Any]   ):

																class    __lowercase							:


																				'''simple docstring'''


																				def __init__( self :  Optional[int]   ):
																										snake_case__							:       List[str]				      =       torch.ones([0]   )





																				def    _lowerCamelCase       ( self :  Optional[int]   ,SCREAMING_SNAKE_CASE_ :  str   ):
																										self.pixel_values.to(SCREAMING_SNAKE_CASE_   )
																										return self







																return Out()

										return extract

				def    _lowerCamelCase       ( self :  Dict   ):
										snake_case__							:       Tuple				      =       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
										snake_case__							:       Union[str, Any]				      =       self.dummy_cond_unet
										snake_case__							:       List[Any]				      =       DDIMScheduler(
										    beta_start=0.00085   ,beta_end=0.012   ,beta_schedule='''scaled_linear'''   ,clip_sample=SCREAMING_SNAKE_CASE_   ,set_alpha_to_one=SCREAMING_SNAKE_CASE_   ,)

										snake_case__							:       Union[str, Any]				      =       self.dummy_vae
										snake_case__							:       Union[str, Any]				      =       self.dummy_text_encoder
										snake_case__							:       Union[str, Any]				      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

										# make sure here that pndm scheduler skips prk
										snake_case__							:       Union[str, Any]				      =       StableDiffusionPipeline(
										    unet=SCREAMING_SNAKE_CASE_   ,scheduler=SCREAMING_SNAKE_CASE_   ,vae=SCREAMING_SNAKE_CASE_   ,text_encoder=SCREAMING_SNAKE_CASE_   ,tokenizer=SCREAMING_SNAKE_CASE_   ,safety_checker=SCREAMING_SNAKE_CASE_   ,feature_extractor=self.dummy_extractor   ,)
										snake_case__							:       Any				      =       sd_pipe.to(SCREAMING_SNAKE_CASE_   )
										sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_   )

										snake_case__							:       Union[str, Any]				      =       '''A painting of a squirrel eating a burger'''

										snake_case__							:       int				      =       torch.Generator(device=SCREAMING_SNAKE_CASE_   ).manual_seed(0   )
										snake_case__							:       List[Any]				      =       sd_pipe([prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=6.0   ,num_inference_steps=2   ,output_type='''np'''   )
										snake_case__							:       List[str]				      =       output.images

										snake_case__							:       Any				      =       torch.Generator(device=SCREAMING_SNAKE_CASE_   ).manual_seed(0   )
										snake_case__							:       Optional[Any]				      =       sd_pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=6.0   ,num_inference_steps=2   ,output_type='''np'''   ,return_dict=SCREAMING_SNAKE_CASE_   ,)[0]

										snake_case__							:       str				      =       image[0, -3:, -3:, -1]
										snake_case__							:       str				      =       image_from_tuple[0, -3:, -3:, -1]

										assert image.shape == (1, 6_4, 6_4, 3)
										snake_case__							:       int				      =       np.array([0.5753, 0.6114, 0.5001, 0.5034, 0.5470, 0.4729, 0.4971, 0.4867, 0.4867]   )

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

				def    _lowerCamelCase       ( self :  Dict   ):
										snake_case__							:       str				      =       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
										snake_case__							:       Optional[Any]				      =       self.dummy_cond_unet
										snake_case__							:       Optional[Any]				      =       PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_   )
										snake_case__							:       Optional[Any]				      =       self.dummy_vae
										snake_case__							:       Any				      =       self.dummy_text_encoder
										snake_case__							:       str				      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

										# make sure here that pndm scheduler skips prk
										snake_case__							:       Dict				      =       StableDiffusionPipeline(
										    unet=SCREAMING_SNAKE_CASE_   ,scheduler=SCREAMING_SNAKE_CASE_   ,vae=SCREAMING_SNAKE_CASE_   ,text_encoder=SCREAMING_SNAKE_CASE_   ,tokenizer=SCREAMING_SNAKE_CASE_   ,safety_checker=SCREAMING_SNAKE_CASE_   ,feature_extractor=self.dummy_extractor   ,)
										snake_case__							:       Any				      =       sd_pipe.to(SCREAMING_SNAKE_CASE_   )
										sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_   )

										snake_case__							:       Dict				      =       '''A painting of a squirrel eating a burger'''
										snake_case__							:       int				      =       torch.Generator(device=SCREAMING_SNAKE_CASE_   ).manual_seed(0   )
										snake_case__							:       Optional[int]				      =       sd_pipe([prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=6.0   ,num_inference_steps=2   ,output_type='''np'''   )

										snake_case__							:       int				      =       output.images

										snake_case__							:       Dict				      =       torch.Generator(device=SCREAMING_SNAKE_CASE_   ).manual_seed(0   )
										snake_case__							:       Optional[int]				      =       sd_pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=6.0   ,num_inference_steps=2   ,output_type='''np'''   ,return_dict=SCREAMING_SNAKE_CASE_   ,)[0]

										snake_case__							:       str				      =       image[0, -3:, -3:, -1]
										snake_case__							:       int				      =       image_from_tuple[0, -3:, -3:, -1]

										assert image.shape == (1, 6_4, 6_4, 3)
										snake_case__							:       Optional[int]				      =       np.array([0.5122, 0.5712, 0.4825, 0.5053, 0.5646, 0.4769, 0.5179, 0.4894, 0.4994]   )

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

				def    _lowerCamelCase       ( self :  List[str]   ):
										snake_case__							:       Optional[Any]				      =       StableDiffusionPipeline.from_pretrained(
										    '''hf-internal-testing/tiny-stable-diffusion-lms-pipe'''   ,safety_checker=SCREAMING_SNAKE_CASE_   )
										assert isinstance(SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_   )
										assert isinstance(pipe.scheduler   ,SCREAMING_SNAKE_CASE_   )
										assert pipe.safety_checker is None

										snake_case__							:       Optional[Any]				      =       pipe('''example prompt'''   ,num_inference_steps=2   ).images[0]
										assert image is not None

										# check that there's no error when saving a pipeline with one of the models being None
										with tempfile.TemporaryDirectory() as tmpdirname:
																pipe.save_pretrained(SCREAMING_SNAKE_CASE_   )
																snake_case__							:       int				      =       StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_   )

										# sanity check that the pipeline still works
										assert pipe.safety_checker is None
										snake_case__							:       Optional[Any]				      =       pipe('''example prompt'''   ,num_inference_steps=2   ).images[0]
										assert image is not None





				@unittest.skipIf(torch_device != '''cuda'''   ,'''This test requires a GPU'''   )
				def    _lowerCamelCase       ( self :  List[Any]   ):
										snake_case__							:       Optional[Any]				      =       self.dummy_cond_unet
										snake_case__							:       int				      =       PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_   )
										snake_case__							:       Dict				      =       self.dummy_vae
										snake_case__							:       Optional[Any]				      =       self.dummy_text_encoder
										snake_case__							:       Union[str, Any]				      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

										# put models in fp16
										snake_case__							:       int				      =       unet.half()
										snake_case__							:       Any				      =       vae.half()
										snake_case__							:       int				      =       bert.half()

										# make sure here that pndm scheduler skips prk
										snake_case__							:       Union[str, Any]				      =       StableDiffusionPipeline(
										    unet=SCREAMING_SNAKE_CASE_   ,scheduler=SCREAMING_SNAKE_CASE_   ,vae=SCREAMING_SNAKE_CASE_   ,text_encoder=SCREAMING_SNAKE_CASE_   ,tokenizer=SCREAMING_SNAKE_CASE_   ,safety_checker=SCREAMING_SNAKE_CASE_   ,feature_extractor=self.dummy_extractor   ,)
										snake_case__							:       Tuple				      =       sd_pipe.to(SCREAMING_SNAKE_CASE_   )
										sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_   )

										snake_case__							:       List[Any]				      =       '''A painting of a squirrel eating a burger'''
										snake_case__							:       Optional[Any]				      =       sd_pipe([prompt]   ,num_inference_steps=2   ,output_type='''np'''   ).images

										assert image.shape == (1, 6_4, 6_4, 3)







@nightly
@require_torch_gpu
class    __lowercase							(      unittest.TestCase						):


				'''simple docstring'''


				def    _lowerCamelCase       ( self :  Any   ):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()

				def    _lowerCamelCase       ( self :  Union[str, Any]   ):
										snake_case__							:       Optional[Any]				      =       '''cuda'''
										snake_case__							:       str				      =       StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''   )
										snake_case__							:       Optional[int]				      =       pipe.to(SCREAMING_SNAKE_CASE_   )
										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_   )

										snake_case__							:       Union[str, Any]				      =       '''a photo of a cat'''
										snake_case__							:       int				      =       {
										    '''editing_prompt''': ['''sunglasses'''],
										    '''reverse_editing_direction''': [False],
										    '''edit_warmup_steps''': 1_0,
										    '''edit_guidance_scale''': 6,
										    '''edit_threshold''': 0.95,
										    '''edit_momentum_scale''': 0.5,
										    '''edit_mom_beta''': 0.6,
										}

										snake_case__							:       Optional[Any]				      =       3
										snake_case__							:       Any				      =       7

										# no sega enabled
										snake_case__							:       str				      =       torch.Generator(SCREAMING_SNAKE_CASE_   )
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       Optional[Any]				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,)

										snake_case__							:       Tuple				      =       output.images
										snake_case__							:       Optional[Any]				      =       image[0, -3:, -3:, -1]
										snake_case__							:       Union[str, Any]				      =       [
										    0.34673113,
										    0.38492733,
										    0.37597352,
										    0.34086335,
										    0.35650748,
										    0.35579205,
										    0.3384763,
										    0.34340236,
										    0.3573271,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

										# with sega enabled
										# generator = torch.manual_seed(seed)
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       Tuple				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,**SCREAMING_SNAKE_CASE_   ,)

										snake_case__							:       int				      =       output.images
										snake_case__							:       int				      =       image[0, -3:, -3:, -1]
										snake_case__							:       Union[str, Any]				      =       [
										    0.41887826,
										    0.37728766,
										    0.30138272,
										    0.41416335,
										    0.41664985,
										    0.36283392,
										    0.36191246,
										    0.43364465,
										    0.43001732,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

				def    _lowerCamelCase       ( self :  int   ):
										snake_case__							:       int				      =       '''cuda'''
										snake_case__							:       Optional[Any]				      =       StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''   )
										snake_case__							:       Optional[int]				      =       pipe.to(SCREAMING_SNAKE_CASE_   )
										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_   )

										snake_case__							:       int				      =       '''an image of a crowded boulevard, realistic, 4k'''
										snake_case__							:       Tuple				      =       {
										    '''editing_prompt''': '''crowd, crowded, people''',
										    '''reverse_editing_direction''': True,
										    '''edit_warmup_steps''': 1_0,
										    '''edit_guidance_scale''': 8.3,
										    '''edit_threshold''': 0.9,
										    '''edit_momentum_scale''': 0.5,
										    '''edit_mom_beta''': 0.6,
										}

										snake_case__							:       Optional[Any]				      =       9
										snake_case__							:       Union[str, Any]				      =       7

										# no sega enabled
										snake_case__							:       Any				      =       torch.Generator(SCREAMING_SNAKE_CASE_   )
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       Optional[int]				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,)

										snake_case__							:       int				      =       output.images
										snake_case__							:       Union[str, Any]				      =       image[0, -3:, -3:, -1]
										snake_case__							:       Union[str, Any]				      =       [
										    0.43497998,
										    0.91814065,
										    0.7540739,
										    0.55580205,
										    0.8467265,
										    0.5389691,
										    0.62574506,
										    0.58897763,
										    0.50926757,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

										# with sega enabled
										# generator = torch.manual_seed(seed)
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       Union[str, Any]				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,**SCREAMING_SNAKE_CASE_   ,)

										snake_case__							:       int				      =       output.images
										snake_case__							:       int				      =       image[0, -3:, -3:, -1]
										snake_case__							:       Any				      =       [
										    0.3089719,
										    0.30500144,
										    0.29016042,
										    0.30630964,
										    0.325687,
										    0.29419225,
										    0.2908091,
										    0.28723598,
										    0.27696294,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

				def    _lowerCamelCase       ( self :  Tuple   ):
										snake_case__							:       Optional[int]				      =       '''cuda'''
										snake_case__							:       Union[str, Any]				      =       StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''   )
										snake_case__							:       Tuple				      =       pipe.to(SCREAMING_SNAKE_CASE_   )
										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_   )

										snake_case__							:       List[str]				      =       '''a castle next to a river'''
										snake_case__							:       Dict				      =       {
										    '''editing_prompt''': ['''boat on a river, boat''', '''monet, impression, sunrise'''],
										    '''reverse_editing_direction''': False,
										    '''edit_warmup_steps''': [1_5, 1_8],
										    '''edit_guidance_scale''': 6,
										    '''edit_threshold''': [0.9, 0.8],
										    '''edit_momentum_scale''': 0.5,
										    '''edit_mom_beta''': 0.6,
										}

										snake_case__							:       Dict				      =       4_8
										snake_case__							:       int				      =       7

										# no sega enabled
										snake_case__							:       Optional[int]				      =       torch.Generator(SCREAMING_SNAKE_CASE_   )
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       List[str]				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,)

										snake_case__							:       str				      =       output.images
										snake_case__							:       int				      =       image[0, -3:, -3:, -1]
										snake_case__							:       List[str]				      =       [
										    0.75163555,
										    0.76037145,
										    0.61785,
										    0.9189673,
										    0.8627701,
										    0.85189694,
										    0.8512813,
										    0.87012076,
										    0.8312857,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

										# with sega enabled
										# generator = torch.manual_seed(seed)
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       List[str]				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,**SCREAMING_SNAKE_CASE_   ,)

										snake_case__							:       Union[str, Any]				      =       output.images
										snake_case__							:       Any				      =       image[0, -3:, -3:, -1]
										snake_case__							:       List[str]				      =       [
										    0.73553365,
										    0.7537271,
										    0.74341905,
										    0.66480356,
										    0.6472925,
										    0.63039416,
										    0.64812905,
										    0.6749717,
										    0.6517102,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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





				def    _lowerCamelCase       ( self :  str   ):
										snake_case__							:       Any				      =       '''cuda'''
										snake_case__							:       Any				      =       StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''   ,torch_dtype=torch.floataa   )
										snake_case__							:       Dict				      =       pipe.to(SCREAMING_SNAKE_CASE_   )
										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_   )

										snake_case__							:       List[Any]				      =       '''a photo of a cat'''
										snake_case__							:       Dict				      =       {
										    '''editing_prompt''': ['''sunglasses'''],
										    '''reverse_editing_direction''': [False],
										    '''edit_warmup_steps''': 1_0,
										    '''edit_guidance_scale''': 6,
										    '''edit_threshold''': 0.95,
										    '''edit_momentum_scale''': 0.5,
										    '''edit_mom_beta''': 0.6,
										}

										snake_case__							:       Dict				      =       3
										snake_case__							:       Optional[int]				      =       7

										# no sega enabled
										snake_case__							:       Dict				      =       torch.Generator(SCREAMING_SNAKE_CASE_   )
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       List[str]				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,)

										snake_case__							:       int				      =       output.images
										snake_case__							:       int				      =       image[0, -3:, -3:, -1]
										snake_case__							:       List[str]				      =       [
										    0.34887695,
										    0.3876953,
										    0.375,
										    0.34423828,
										    0.3581543,
										    0.35717773,
										    0.3383789,
										    0.34570312,
										    0.359375,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

										# with sega enabled
										# generator = torch.manual_seed(seed)
										generator.manual_seed(SCREAMING_SNAKE_CASE_   )
										snake_case__							:       Tuple				      =       pipe(
										    [prompt]   ,generator=SCREAMING_SNAKE_CASE_   ,guidance_scale=SCREAMING_SNAKE_CASE_   ,num_inference_steps=5_0   ,output_type='''np'''   ,width=5_1_2   ,height=5_1_2   ,**SCREAMING_SNAKE_CASE_   ,)

										snake_case__							:       Union[str, Any]				      =       output.images
										snake_case__							:       Tuple				      =       image[0, -3:, -3:, -1]
										snake_case__							:       Tuple				      =       [
										    0.42285156,
										    0.36914062,
										    0.29077148,
										    0.42041016,
										    0.41918945,
										    0.35498047,
										    0.3618164,
										    0.4423828,
										    0.43115234,
										]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

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


