import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
    datefmt='''%m/%d/%Y %H:%M:%S''',
    level=logging.INFO,
)
_lowerCamelCase    :      List[str]	 =						logging.getLogger(__name__)

_lowerCamelCase    :      Optional[int]	 =						int(1_00_00)  # Hardcoded max length to avoid infinite loop

_lowerCamelCase    :      Optional[int]	 =						{
    '''gpt2''': (GPTaLMHeadModel, GPTaTokenizer),
    '''ctrl''': (CTRLLMHeadModel, CTRLTokenizer),
    '''openai-gpt''': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    '''xlnet''': (XLNetLMHeadModel, XLNetTokenizer),
    '''transfo-xl''': (TransfoXLLMHeadModel, TransfoXLTokenizer),
    '''xlm''': (XLMWithLMHeadModel, XLMTokenizer),
    '''gptj''': (GPTJForCausalLM, AutoTokenizer),
    '''bloom''': (BloomForCausalLM, BloomTokenizerFast),
    '''llama''': (LlamaForCausalLM, LlamaTokenizer),
    '''opt''': (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
_lowerCamelCase    :      str	 =						'''In 1991, the remains of Russian Tsar Nicholas II and his family
(except for Alexei and Maria) are discovered.
The voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the
remainder of the story. 1883 Western Siberia,
a young Grigori Rasputin is asked by his father and a group of men to perform magic.
Rasputin has a vision and denounces one of the men as a horse thief. Although his
father initially slaps him for making such an accusation, Rasputin watches as the
man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>'''





def 		__lowerCamelCase							(UpperCAmelCase__   :							str     ):
					np.random.seed(args.seed     )
					torch.manual_seed(args.seed     )
					if args.n_gpu > 0:
										torch.cuda.manual_seed_all(args.seed     )





def 		__lowerCamelCase							(UpperCAmelCase__   :							Optional[Any]					,       UpperCAmelCase__   :							int					,       UpperCAmelCase__   :							Optional[Any]					,       UpperCAmelCase__   :							Optional[Any]     ):
					if args.temperature > 0.7:
										logger.info("CTRL typically works better with lower temperatures (and lower top_k)."     )

					SCREAMING_SNAKE_CASE				=				tokenizer.encode(UpperCAmelCase__					,       add_special_tokens=UpperCAmelCase__     )
					if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()     ):
										logger.info("WARNING! You are not starting your generation from a control code so you won't get good results"     )
					return prompt_text





def 		__lowerCamelCase							(UpperCAmelCase__   :							List[Any]					,       UpperCAmelCase__   :							Tuple					,       UpperCAmelCase__   :							List[Any]					,       UpperCAmelCase__   :							Optional[int]     ):
					# kwargs = {"language": None, "mask_token_id": None}

					# Set the language
					SCREAMING_SNAKE_CASE				=				hasattr(model.config					,       "use_lang_emb"     ) and model.config.use_lang_emb
					if hasattr(model.config					,       "lang2id"     ) and use_lang_emb:
										SCREAMING_SNAKE_CASE				=				model.config.langaid.keys()
										if args.xlm_language in available_languages:
															SCREAMING_SNAKE_CASE				=				args.xlm_language
										else:
															SCREAMING_SNAKE_CASE				=				None
															while language not in available_languages:
																				SCREAMING_SNAKE_CASE				=				input("Using XLM. Select language in " + str(list(UpperCAmelCase__     )     ) + " >>> "     )

										SCREAMING_SNAKE_CASE				=				model.config.langaid[language]
										# kwargs["language"] = tokenizer.lang2id[language]

					# TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
					# XLM masked-language modeling (MLM) models need masked token
					# is_xlm_mlm = "mlm" in args.model_name_or_path
					# if is_xlm_mlm:
					#     kwargs["mask_token_id"] = tokenizer.mask_token_id

					return prompt_text





def 		__lowerCamelCase							(UpperCAmelCase__   :							Any					,       UpperCAmelCase__   :							Dict					,       UpperCAmelCase__   :							Union[str, Any]					,       UpperCAmelCase__   :							Union[str, Any]     ):
					SCREAMING_SNAKE_CASE				=				args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
					SCREAMING_SNAKE_CASE				=				prefix + prompt_text
					return prompt_text





def 		__lowerCamelCase							(UpperCAmelCase__   :							Union[str, Any]					,       UpperCAmelCase__   :							str					,       UpperCAmelCase__   :							str					,       UpperCAmelCase__   :							Any     ):
					SCREAMING_SNAKE_CASE				=				args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
					SCREAMING_SNAKE_CASE				=				prefix + prompt_text
					return prompt_text


_lowerCamelCase    :      List[str]	 =						{
    '''ctrl''': prepare_ctrl_input,
    '''xlm''': prepare_xlm_input,
    '''xlnet''': prepare_xlnet_input,
    '''transfo-xl''': prepare_transfoxl_input,
}





def 		__lowerCamelCase							(UpperCAmelCase__   :							Tuple					,       UpperCAmelCase__   :							int     ):
					if length < 0 and max_sequence_length > 0:
										SCREAMING_SNAKE_CASE				=				max_sequence_length
					elif 0 < max_sequence_length < length:
										SCREAMING_SNAKE_CASE				=				max_sequence_length  # No generation bigger than model size
					elif length < 0:
										SCREAMING_SNAKE_CASE				=				MAX_LENGTH  # avoid infinite loop
					return length





def 		__lowerCamelCase							(UpperCAmelCase__   :							List[Any]     ):
					SCREAMING_SNAKE_CASE				=				None
					if hasattr(UpperCAmelCase__					,       "hidden_size"     ):
										SCREAMING_SNAKE_CASE				=				model_config.hidden_size
					elif hasattr(UpperCAmelCase__					,       "n_embed"     ):
										SCREAMING_SNAKE_CASE				=				model_config.n_embed
					elif hasattr(UpperCAmelCase__					,       "n_embd"     ):
										SCREAMING_SNAKE_CASE				=				model_config.n_embd

					SCREAMING_SNAKE_CASE				=				None
					if hasattr(UpperCAmelCase__					,       "num_attention_heads"     ):
										SCREAMING_SNAKE_CASE				=				model_config.num_attention_heads
					elif hasattr(UpperCAmelCase__					,       "n_head"     ):
										SCREAMING_SNAKE_CASE				=				model_config.n_head

					if embedding_size is None or num_head is None or num_head == 0:
										raise ValueError("Check the model config"     )

					SCREAMING_SNAKE_CASE				=				int(embedding_size / num_head     )
					if hasattr(UpperCAmelCase__					,       "n_layer"     ):
										SCREAMING_SNAKE_CASE				=				model_config.n_layer
					elif hasattr(UpperCAmelCase__					,       "num_hidden_layers"     ):
										SCREAMING_SNAKE_CASE				=				model_config.num_hidden_layers
					else:
										raise ValueError("Number of hidden layers couldn't be determined from the model config"     )

					return num_layer, num_head, num_embedding_size_per_head





def 		__lowerCamelCase							(UpperCAmelCase__   :							List[str]					,       UpperCAmelCase__   :							Union[str, Any]					,       UpperCAmelCase__   :							List[Any]     ):
					SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				sparse_model_config(model.config     )
					if model.config.model_type == "bloom":
										SCREAMING_SNAKE_CASE				=				tuple(
										    (
										        torch.empty(int(num_attention_heads * batch_size     )					,       UpperCAmelCase__					,       UpperCAmelCase__     )
										        .to(model.dtype     )
										        .to(model.device     ),
										        torch.empty(int(num_attention_heads * batch_size     )					,       UpperCAmelCase__					,       UpperCAmelCase__     )
										        .to(model.dtype     )
										        .to(model.device     ),
										    )
										    for _ in range(UpperCAmelCase__     )     )
					else:
										SCREAMING_SNAKE_CASE				=				tuple(
										    (
										        torch.empty(UpperCAmelCase__					,       UpperCAmelCase__					,       UpperCAmelCase__					,       UpperCAmelCase__     )
										        .to(model.dtype     )
										        .to(model.device     ),
										        torch.empty(UpperCAmelCase__					,       UpperCAmelCase__					,       UpperCAmelCase__					,       UpperCAmelCase__     )
										        .to(model.dtype     )
										        .to(model.device     ),
										    )
										    for _ in range(UpperCAmelCase__     )     )
					return past_key_values





def 		__lowerCamelCase							(UpperCAmelCase__   :							int					,       UpperCAmelCase__   :							Dict					,       UpperCAmelCase__   :							List[str]     ):
					SCREAMING_SNAKE_CASE				=				len(UpperCAmelCase__     )
					SCREAMING_SNAKE_CASE				=				tokenizer.batch_encode_plus(UpperCAmelCase__					,       return_tensors="pt"     )
					SCREAMING_SNAKE_CASE				=				dummy_input.to(model.device     )
					if model.config.use_cache:
										SCREAMING_SNAKE_CASE				=				generate_past_key_values(UpperCAmelCase__					,       UpperCAmelCase__					,       1     )
					SCREAMING_SNAKE_CASE				=				torch.cat(
					    [
					        torch.zeros(dummy_input["attention_mask"].shape[0]					,       1     )
					        .to(dummy_input["attention_mask"].dtype     )
					        .to(model.device     ),
					        dummy_input["attention_mask"],
					    ]					,       -1					,       )
					return dummy_input


class   lowercase			(   a   ):
							lowercase__  :				str									=							("""_optimized""", """_default""")




							def __init__(  self      :    Optional[Any]		,							_UpperCamelCase      :    str		,							_UpperCamelCase      :    List[str]					)    -> Any:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				optimized
												SCREAMING_SNAKE_CASE				=				default




							def __call__(  self      :    List[str]		,							*_UpperCamelCase      :    Optional[int]		,							**_UpperCamelCase      :    Optional[int]					)    -> Union[str, Any]:



												'''simple docstring'''

												if kwargs["past_key_values"] is None and self._default.config.use_cache:
																	SCREAMING_SNAKE_CASE				=				generate_past_key_values(self._default		,							kwargs["input_ids"].shape[0]		,							0					)
												kwargs.pop("position_ids"		,							_UpperCamelCase					)
												for k in list(kwargs.keys()					):
																	if kwargs[k] is None or isinstance(kwargs[k]		,							_UpperCamelCase					):
																						kwargs.pop(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				self._optimized(**_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				outputs[0]
												SCREAMING_SNAKE_CASE				=				outputs[1]
												SCREAMING_SNAKE_CASE				=				CausalLMOutputWithPast(
												    loss=_UpperCamelCase		,							logits=_UpperCamelCase		,							past_key_values=_UpperCamelCase		,							hidden_states=_UpperCamelCase		,							attentions=_UpperCamelCase		,							)
												return fixed_output




							def __getattr__(  self      :    Tuple		,							_UpperCamelCase      :    List[str]					)    -> Any:



												'''simple docstring'''

												return getattr(self._default		,							_UpperCamelCase					)




							def 		__snake_case(  self      :    List[str]		,							_UpperCamelCase      :    Optional[int]		,							_UpperCamelCase      :    str=None		,							_UpperCamelCase      :    int=None		,							_UpperCamelCase      :    Optional[Any]=None		,							**_UpperCamelCase      :    Optional[Any]					)    -> Optional[Any]:



												'''simple docstring'''

												return self._default.prepare_inputs_for_generation(
												    _UpperCamelCase		,							past_key_values=_UpperCamelCase		,							inputs_embeds=_UpperCamelCase		,							use_cache=_UpperCamelCase		,							**_UpperCamelCase					)





							def 		__snake_case(  self      :    str		,							_UpperCamelCase      :    Tuple[Tuple[torch.Tensor]]		,							_UpperCamelCase      :    torch.Tensor					)    -> Tuple[Tuple[torch.Tensor]]:



												'''simple docstring'''

												return self._default._reorder_cache(_UpperCamelCase		,							_UpperCamelCase					)





def 		__lowerCamelCase							():
					SCREAMING_SNAKE_CASE				=				argparse.ArgumentParser()
					parser.add_argument(
					    "--model_type"					,       default=UpperCAmelCase__					,       type=UpperCAmelCase__					,       required=UpperCAmelCase__					,       help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()     )					,       )
					parser.add_argument(
					    "--model_name_or_path"					,       default=UpperCAmelCase__					,       type=UpperCAmelCase__					,       required=UpperCAmelCase__					,       help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(MODEL_CLASSES.keys()     )					,       )

					parser.add_argument("--prompt"					,       type=UpperCAmelCase__					,       default=""     )
					parser.add_argument("--length"					,       type=UpperCAmelCase__					,       default=2_0     )
					parser.add_argument("--stop_token"					,       type=UpperCAmelCase__					,       default=UpperCAmelCase__					,       help="Token at which text generation is stopped"     )

					parser.add_argument(
					    "--temperature"					,       type=UpperCAmelCase__					,       default=1.0					,       help="temperature of 1.0 has no effect, lower tend toward greedy sampling"					,       )
					parser.add_argument(
					    "--repetition_penalty"					,       type=UpperCAmelCase__					,       default=1.0					,       help="primarily useful for CTRL model; in that case, use 1.2"     )
					parser.add_argument("--k"					,       type=UpperCAmelCase__					,       default=0     )
					parser.add_argument("--p"					,       type=UpperCAmelCase__					,       default=0.9     )

					parser.add_argument("--prefix"					,       type=UpperCAmelCase__					,       default=""					,       help="Text added prior to input."     )
					parser.add_argument("--padding_text"					,       type=UpperCAmelCase__					,       default=""					,       help="Deprecated, the use of `--prefix` is preferred."     )
					parser.add_argument("--xlm_language"					,       type=UpperCAmelCase__					,       default=""					,       help="Optional language when used with the XLM model."     )

					parser.add_argument("--seed"					,       type=UpperCAmelCase__					,       default=4_2					,       help="random seed for initialization"     )
					parser.add_argument("--no_cuda"					,       action="store_true"					,       help="Avoid using CUDA when available"     )
					parser.add_argument("--num_return_sequences"					,       type=UpperCAmelCase__					,       default=1					,       help="The number of samples to generate."     )
					parser.add_argument(
					    "--fp16"					,       action="store_true"					,       help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"					,       )
					parser.add_argument("--jit"					,       action="store_true"					,       help="Whether or not to use jit trace to accelerate inference"     )
					SCREAMING_SNAKE_CASE				=				parser.parse_args()

					SCREAMING_SNAKE_CASE				=				torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"     )
					SCREAMING_SNAKE_CASE				=				0 if args.no_cuda else torch.cuda.device_count()

					logger.warning(F"device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}"     )

					set_seed(UpperCAmelCase__     )

					# Initialize the model and tokenizer
					try:
										SCREAMING_SNAKE_CASE				=				args.model_type.lower()
										SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				MODEL_CLASSES[args.model_type]
					except KeyError:
										raise KeyError("the model {} you specified is not supported. You are welcome to add it and open a PR :)"     )

					SCREAMING_SNAKE_CASE				=				tokenizer_class.from_pretrained(args.model_name_or_path     )
					if tokenizer.pad_token is None:
										SCREAMING_SNAKE_CASE				=				tokenizer.eos_token
					SCREAMING_SNAKE_CASE				=				model_class.from_pretrained(args.model_name_or_path     )
					model.to(args.device     )

					if args.fpaa:
										model.half()
					SCREAMING_SNAKE_CASE				=				getattr(model.config					,       "max_position_embeddings"					,       0     )
					SCREAMING_SNAKE_CASE				=				adjust_length_to_model(args.length					,       max_sequence_length=UpperCAmelCase__     )
					logger.info(UpperCAmelCase__     )

					SCREAMING_SNAKE_CASE				=				args.prompt if args.prompt else input("Model prompt >>> "     )

					# Different models need different input formatting and/or extra arguments
					SCREAMING_SNAKE_CASE				=				args.model_type in PREPROCESSING_FUNCTIONS.keys()
					if requires_preprocessing:
										SCREAMING_SNAKE_CASE				=				PREPROCESSING_FUNCTIONS.get(args.model_type     )
										SCREAMING_SNAKE_CASE				=				prepare_input(UpperCAmelCase__					,       UpperCAmelCase__					,       UpperCAmelCase__					,       UpperCAmelCase__     )

										if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
															SCREAMING_SNAKE_CASE				=				{"add_space_before_punct_symbol": True}
										else:
															SCREAMING_SNAKE_CASE				=				{}

										SCREAMING_SNAKE_CASE				=				tokenizer.encode(
										    UpperCAmelCase__					,       add_special_tokens=UpperCAmelCase__					,       return_tensors="pt"					,       **UpperCAmelCase__     )
					else:
										SCREAMING_SNAKE_CASE				=				args.prefix if args.prefix else args.padding_text
										SCREAMING_SNAKE_CASE				=				tokenizer.encode(prefix + prompt_text					,       add_special_tokens=UpperCAmelCase__					,       return_tensors="pt"     )
					SCREAMING_SNAKE_CASE				=				encoded_prompt.to(args.device     )

					if encoded_prompt.size()[-1] == 0:
										SCREAMING_SNAKE_CASE				=				None
					else:
										SCREAMING_SNAKE_CASE				=				encoded_prompt

					if args.jit:
										SCREAMING_SNAKE_CASE				=				["enable jit"]
										SCREAMING_SNAKE_CASE				=				prepare_jit_inputs(UpperCAmelCase__					,       UpperCAmelCase__					,       UpperCAmelCase__     )
										torch._C._jit_set_texpr_fuser_enabled(UpperCAmelCase__     )
										SCREAMING_SNAKE_CASE				=				False
										if hasattr(UpperCAmelCase__					,       "forward"     ):
															SCREAMING_SNAKE_CASE				=				inspect.signature(model.forward     )
										else:
															SCREAMING_SNAKE_CASE				=				inspect.signature(model.__call__     )
										SCREAMING_SNAKE_CASE				=				tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(UpperCAmelCase__					,       UpperCAmelCase__     ) is not None     )
										SCREAMING_SNAKE_CASE				=				torch.jit.trace(UpperCAmelCase__					,       UpperCAmelCase__					,       strict=UpperCAmelCase__     )
										SCREAMING_SNAKE_CASE				=				torch.jit.freeze(traced_model.eval()     )
										traced_model(*UpperCAmelCase__     )
										traced_model(*UpperCAmelCase__     )

										SCREAMING_SNAKE_CASE				=				_ModelFallbackWrapper(UpperCAmelCase__					,       UpperCAmelCase__     )

					SCREAMING_SNAKE_CASE				=				model.generate(
					    input_ids=UpperCAmelCase__					,       max_length=args.length + len(encoded_prompt[0]     )					,       temperature=args.temperature					,       top_k=args.k					,       top_p=args.p					,       repetition_penalty=args.repetition_penalty					,       do_sample=UpperCAmelCase__					,       num_return_sequences=args.num_return_sequences					,       )

					# Remove the batch dimension when returning multiple sequences
					if len(output_sequences.shape     ) > 2:
										output_sequences.squeeze_()

					SCREAMING_SNAKE_CASE				=				[]

					for generated_sequence_idx, generated_sequence in enumerate(UpperCAmelCase__     ):
										print(F"=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==="     )
										SCREAMING_SNAKE_CASE				=				generated_sequence.tolist()

										# Decode text
										SCREAMING_SNAKE_CASE				=				tokenizer.decode(UpperCAmelCase__					,       clean_up_tokenization_spaces=UpperCAmelCase__     )

										# Remove all text after the stop token
										SCREAMING_SNAKE_CASE				=				text[: text.find(args.stop_token     ) if args.stop_token else None]

										# Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
										SCREAMING_SNAKE_CASE				=				(
										    prompt_text + text[len(tokenizer.decode(encoded_prompt[0]					,       clean_up_tokenization_spaces=UpperCAmelCase__     )     ) :]
										)

										generated_sequences.append(UpperCAmelCase__     )
										print(UpperCAmelCase__     )

					return generated_sequences


if __name__ == "__main__":
							main()





import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class   lowercase			(   a ,				a ,				unittest.TestCase   ):
							lowercase__  :				Optional[Any]									=							StableDiffusionParadigmsPipeline
							lowercase__  :				Optional[Any]									=							TEXT_TO_IMAGE_PARAMS
							lowercase__  :				Union[str, Any]									=							TEXT_TO_IMAGE_BATCH_PARAMS
							lowercase__  :				int									=							TEXT_TO_IMAGE_IMAGE_PARAMS
							lowercase__  :				List[Any]									=							TEXT_TO_IMAGE_IMAGE_PARAMS




							def 		__snake_case(  self      :    Tuple					)    -> List[Any]:



												'''simple docstring'''

												torch.manual_seed(0					)
												SCREAMING_SNAKE_CASE				=				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		,							attention_head_dim=(2, 4)		,							use_linear_projection=_UpperCamelCase		,							)
												SCREAMING_SNAKE_CASE				=				DDIMParallelScheduler(
												    beta_start=0.0_0_0_8_5		,							beta_end=0.0_1_2		,							beta_schedule="scaled_linear"		,							clip_sample=_UpperCamelCase		,							set_alpha_to_one=_UpperCamelCase		,							)
												torch.manual_seed(0					)
												SCREAMING_SNAKE_CASE				=				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		,							sample_size=128		,							)
												torch.manual_seed(0					)
												SCREAMING_SNAKE_CASE				=				CLIPTextConfig(
												    bos_token_id=0		,							eos_token_id=2		,							hidden_size=32		,							intermediate_size=37		,							layer_norm_eps=1e-05		,							num_attention_heads=4		,							num_hidden_layers=5		,							pad_token_id=1		,							vocab_size=1_000		,							hidden_act="gelu"		,							projection_dim=512		,							)
												SCREAMING_SNAKE_CASE				=				CLIPTextModel(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)

												SCREAMING_SNAKE_CASE				=				{
												    "unet": unet,
												    "scheduler": scheduler,
												    "vae": vae,
												    "text_encoder": text_encoder,
												    "tokenizer": tokenizer,
												    "safety_checker": None,
												    "feature_extractor": None,
												}
												return components




							def 		__snake_case(  self      :    Any		,							_UpperCamelCase      :    List[str]		,							_UpperCamelCase      :    Any=0					)    -> Optional[int]:



												'''simple docstring'''

												if str(_UpperCamelCase					).startswith("mps"					):
																	SCREAMING_SNAKE_CASE				=				torch.manual_seed(_UpperCamelCase					)
												else:
																	SCREAMING_SNAKE_CASE				=				torch.Generator(device=_UpperCamelCase					).manual_seed(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				{
												    "prompt": "a photograph of an astronaut riding a horse",
												    "generator": generator,
												    "num_inference_steps": 10,
												    "guidance_scale": 6.0,
												    "output_type": "numpy",
												    "parallel": 3,
												    "debug": True,
												}
												return inputs




							def 		__snake_case(  self      :    Optional[Any]					)    -> Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"cpu"  # ensure determinism for the device-dependent torch.Generator
												SCREAMING_SNAKE_CASE				=				self.get_dummy_components()
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline(**_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe.to(_UpperCamelCase					)
												sd_pipe.set_progress_bar_config(disable=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				self.get_dummy_inputs(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe(**_UpperCamelCase					).images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1]
												assert image.shape == (1, 64, 64, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.4_7_7_3, 0.5_4_1_7, 0.4_7_2_3, 0.4_9_2_5, 0.5_6_3_1, 0.4_7_5_2, 0.5_2_4_0, 0.4_9_3_5, 0.5_0_2_3]					)

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




							def 		__snake_case(  self      :    Optional[Any]					)    -> List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"cpu"  # ensure determinism for the device-dependent torch.Generator
												SCREAMING_SNAKE_CASE				=				self.get_dummy_components()
												torch.manual_seed(0					)
												SCREAMING_SNAKE_CASE				=				DDPMParallelScheduler()
												torch.manual_seed(0					)
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline(**_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe.to(_UpperCamelCase					)
												sd_pipe.set_progress_bar_config(disable=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				self.get_dummy_inputs(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe(**_UpperCamelCase					).images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1]
												assert image.shape == (1, 64, 64, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.3_5_7_3, 0.4_4_2_0, 0.4_9_6_0, 0.4_7_9_9, 0.3_7_9_6, 0.3_8_7_9, 0.4_8_1_9, 0.4_3_6_5, 0.4_4_6_8]					)

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




							def 		__snake_case(  self      :    Tuple					)    -> int:



												'''simple docstring'''

												super().test_inference_batch_consistent(batch_sizes=[1, 2]					)




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



												'''simple docstring'''

												super().test_inference_batch_single_identical(batch_size=2		,							expected_max_diff=3e-3					)





							def 		__snake_case(  self      :    List[Any]					)    -> str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"cpu"  # ensure determinism for the device-dependent torch.Generator
												SCREAMING_SNAKE_CASE				=				self.get_dummy_components()
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline(**_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe.to(_UpperCamelCase					)
												sd_pipe.set_progress_bar_config(disable=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				self.get_dummy_inputs(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				"french fries"
												SCREAMING_SNAKE_CASE				=				sd_pipe(**_UpperCamelCase		,							negative_prompt=_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				output.images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1]

												assert image.shape == (1, 64, 64, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.4_7_7_1, 0.5_4_2_0, 0.4_6_8_3, 0.4_9_1_8, 0.5_6_3_6, 0.4_7_2_5, 0.5_2_3_0, 0.4_9_2_3, 0.5_0_1_5]					)

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



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




							def 		__snake_case(  self      :    List[str]					)    -> List[Any]:



												'''simple docstring'''

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




							def 		__snake_case(  self      :    Optional[Any]		,							_UpperCamelCase      :    int=0					)    -> Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				torch.Generator(device=_UpperCamelCase					).manual_seed(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				{
												    "prompt": "a photograph of an astronaut riding a horse",
												    "generator": generator,
												    "num_inference_steps": 10,
												    "guidance_scale": 7.5,
												    "output_type": "numpy",
												    "parallel": 3,
												    "debug": True,
												}
												return inputs





							def 		__snake_case(  self      :    Dict					)    -> str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"stabilityai/stable-diffusion-2-base"
												SCREAMING_SNAKE_CASE				=				DDIMParallelScheduler.from_pretrained(_UpperCamelCase		,							subfolder="scheduler"					)
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline.from_pretrained(_UpperCamelCase		,							scheduler=_UpperCamelCase		,							safety_checker=_UpperCamelCase					)
												pipe.to(_UpperCamelCase					)
												pipe.set_progress_bar_config(disable=_UpperCamelCase					)
												pipe.enable_attention_slicing()

												SCREAMING_SNAKE_CASE				=				self.get_inputs()
												SCREAMING_SNAKE_CASE				=				pipe(**_UpperCamelCase					).images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 512, 512, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.9_6_2_2, 0.9_6_0_2, 0.9_7_4_8, 0.9_5_9_1, 0.9_6_3_0, 0.9_6_9_1, 0.9_6_6_1, 0.9_6_3_1, 0.9_7_4_1]					)

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




