






import json
import logging
import math
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

from datasets import Dataset, load_dataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_FOR_MASKED_LM_MAPPING,
    AutoConfig,
    AutoModelForMaskedLM,
    AutoTokenizer,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


UpperCamelCase								=		logging.getLogger(__name__)
UpperCamelCase								=		list(MODEL_FOR_MASKED_LM_MAPPING.keys())
UpperCamelCase								=		tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class 				lowerCAmelCase_	:
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={
				        "help": (
				            "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."
				        )
				    }   ,		)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(__SCREAMING_SNAKE_CASE			)}   ,		)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={
				        "help": (
				            "Override some existing default config settings when a model is trained from scratch. Example: "
				            "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
				        )
				    }   ,		)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "Pretrained config name or path if not the same as model_name"}			)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}			)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}   ,		)
				_UpperCamelCase					:       bool							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}   ,		)
				_UpperCamelCase					:       str							       = field(
				    default="main"   ,		metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}   ,		)
				_UpperCamelCase					:       bool							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={
				        "help": (
				            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
				            "with private models)."
				        )
				    }   ,		)


				def 						__a					(					self      ):







											if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
																		raise ValueError(
																		    '--config_overrides can\'t be used in combination with --config_name or --model_name_or_path'      )




@dataclass
class 				lowerCAmelCase_	:
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "The name of the dataset to use (via the datasets library)."}			)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}			)
				_UpperCamelCase					:       Optional[str]							       = field(default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "The input training data file (a text file)."}			)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}   ,		)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "An optional input train ref data file for whole word masking in Chinese."}   ,		)
				_UpperCamelCase					:       Optional[str]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."}   ,		)
				_UpperCamelCase					:       bool							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "Overwrite the cached training and evaluation sets"}			)
				_UpperCamelCase					:       Optional[int]							       = field(
				    default=5   ,		metadata={
				        "help": "The percentage of the train set used as validation set in case there's no validation split"
				    }   ,		)
				_UpperCamelCase					:       Optional[int]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={
				        "help": (
				            "The maximum total input sequence length after tokenization. Sequences longer "
				            "than this will be truncated. Default to the max input length of the model."
				        )
				    }   ,		)
				_UpperCamelCase					:       Optional[int]							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={"help": "The number of processes to use for the preprocessing."}   ,		)
				_UpperCamelCase					:       float							       = field(
				    default=0.1_5   ,		metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}			)
				_UpperCamelCase					:       bool							       = field(
				    default=__SCREAMING_SNAKE_CASE   ,		metadata={
				        "help": (
				            "Whether to pad all samples to `max_seq_length`. "
				            "If False, will pad the samples dynamically when batching to the maximum length in the batch."
				        )
				    }   ,		)


				def 						__a					(					self      ):







											if self.train_file is not None:
																		_lowercase							:   Tuple 							=   self.train_file.split('.'      )[-1]
																		assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
											if self.validation_file is not None:
																		_lowercase							:   int 							=   self.validation_file.split('.'      )[-1]
																		assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."






def    __magic_name__    (	SCREAMING_SNAKE_CASE     ,     SCREAMING_SNAKE_CASE				)     ->    Optional[Any]:
							with open(SCREAMING_SNAKE_CASE     ,     'r'     ,     encoding='utf-8'				) as f:
														_lowercase							:   Optional[int] 							=   [json.loads(SCREAMING_SNAKE_CASE				) for line in f.read().splitlines() if (len(SCREAMING_SNAKE_CASE				) > 0 and not line.isspace())]
							assert len(SCREAMING_SNAKE_CASE				) == len(SCREAMING_SNAKE_CASE				)

							_lowercase							:   Optional[int] 							=   {c: dataset[c] for c in dataset.column_names}
							_lowercase							:   Optional[int] 							=   refs
							return Dataset.from_dict(SCREAMING_SNAKE_CASE				)






def    __magic_name__    (	)     ->    List[str]:
							# See all possible arguments in src/transformers/training_args.py
							# or by passing the --help flag to this script.
							# We now keep distinct sets of args, for a cleaner separation of concerns.

							_lowercase							:   int 							=   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
							if len(sys.argv				) == 2 and sys.argv[1].endswith('.json'				):
														# If we pass only one argument to the script and it's the path to a json file,
														# let's parse it to get our arguments.
														_lowercase							:   Tuple 							=   parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
							else:
														_lowercase							:   Tuple 							=   parser.parse_args_into_dataclasses()

							# Detecting last checkpoint.
							_lowercase							:   Any 							=   None
							if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
														_lowercase							:   Any 							=   get_last_checkpoint(training_args.output_dir				)
														if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
																					raise ValueError(
																					    F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
																					    'Use --overwrite_output_dir to overcome.'				)
														elif last_checkpoint is not None:
																					logger.info(
																					    F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
																					    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'				)

    # Setup logging
							logging.basicConfig(
							    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'     ,     datefmt='%m/%d/%Y %H:%M:%S'     ,     handlers=[logging.StreamHandler(sys.stdout				)]     ,     )
							logger.setLevel(logging.INFO if is_main_process(training_args.local_rank				) else logging.WARN				)

							# Log on each process the small summary:
							logger.warning(
							    F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
							    + F"""distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}"""				)
							# Set the verbosity to info of the Transformers logger (on main process only):
							if is_main_process(training_args.local_rank				):
														transformers.utils.logging.set_verbosity_info()
														transformers.utils.logging.enable_default_handler()
														transformers.utils.logging.enable_explicit_format()
							logger.info('Training/evaluation parameters %s'     ,     SCREAMING_SNAKE_CASE				)

							# Set seed before initializing model.
							set_seed(training_args.seed				)

							# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
							# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
							# (the dataset will be downloaded automatically from the datasets Hub).
							#
							# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
							# 'text' is found. You can easily tweak this behavior (see below).
							#
							# In distributed training, the load_dataset function guarantee that only one local process can concurrently
							# download the dataset.
							if data_args.dataset_name is not None:
														# Downloading and loading a dataset from the hub.
														_lowercase							:   Any 							=   load_dataset(data_args.dataset_name     ,     data_args.dataset_config_name				)
														if "validation" not in datasets.keys():
																					_lowercase							:   Optional[Any] 							=   load_dataset(
																					    data_args.dataset_name     ,     data_args.dataset_config_name     ,     split=F"""train[:{data_args.validation_split_percentage}%]"""     ,     )
																					_lowercase							:   List[Any] 							=   load_dataset(
																					    data_args.dataset_name     ,     data_args.dataset_config_name     ,     split=F"""train[{data_args.validation_split_percentage}%:]"""     ,     )
							else:
														_lowercase							:   int 							=   {}
														if data_args.train_file is not None:
																					_lowercase							:   Optional[Any] 							=   data_args.train_file
														if data_args.validation_file is not None:
																					_lowercase							:   Union[str, Any] 							=   data_args.validation_file
														_lowercase							:   Union[str, Any] 							=   data_args.train_file.split('.'				)[-1]
														if extension == "txt":
																					_lowercase							:   str 							=   """text"""
														_lowercase							:   Union[str, Any] 							=   load_dataset(SCREAMING_SNAKE_CASE     ,     data_files=SCREAMING_SNAKE_CASE				)
							# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
							# https://huggingface.co/docs/datasets/loading_datasets.html.

							# Load pretrained model and tokenizer
							#
							# Distributed training:
							# The .from_pretrained methods guarantee that only one local process can concurrently
							# download model & vocab.
							_lowercase							:   Optional[int] 							=   {
							    """cache_dir""": model_args.cache_dir,
							    """revision""": model_args.model_revision,
							    """use_auth_token""": True if model_args.use_auth_token else None,
							}
							if model_args.config_name:
														_lowercase							:   Any 							=   AutoConfig.from_pretrained(model_args.config_name     ,     **SCREAMING_SNAKE_CASE				)
							elif model_args.model_name_or_path:
														_lowercase							:   str 							=   AutoConfig.from_pretrained(model_args.model_name_or_path     ,     **SCREAMING_SNAKE_CASE				)
							else:
														_lowercase							:   Any 							=   CONFIG_MAPPING[model_args.model_type]()
														logger.warning('You are instantiating a new config instance from scratch.'				)
														if model_args.config_overrides is not None:
																					logger.info(F"""Overriding config: {model_args.config_overrides}"""				)
																					config.update_from_string(model_args.config_overrides				)
																					logger.info(F"""New config: {config}"""				)

							_lowercase							:   Optional[Any] 							=   {
							    """cache_dir""": model_args.cache_dir,
							    """use_fast""": model_args.use_fast_tokenizer,
							    """revision""": model_args.model_revision,
							    """use_auth_token""": True if model_args.use_auth_token else None,
							}
							if model_args.tokenizer_name:
														_lowercase							:   Optional[Any] 							=   AutoTokenizer.from_pretrained(model_args.tokenizer_name     ,     **SCREAMING_SNAKE_CASE				)
							elif model_args.model_name_or_path:
														_lowercase							:   List[str] 							=   AutoTokenizer.from_pretrained(model_args.model_name_or_path     ,     **SCREAMING_SNAKE_CASE				)
							else:
														raise ValueError(
														    'You are instantiating a new tokenizer from scratch. This is not supported by this script.'
														    'You can do it from another script, save it, and load it from here, using --tokenizer_name.'				)

							if model_args.model_name_or_path:
														_lowercase							:   List[Any] 							=   AutoModelForMaskedLM.from_pretrained(
														    model_args.model_name_or_path     ,     from_tf=bool('.ckpt' in model_args.model_name_or_path				)     ,     config=SCREAMING_SNAKE_CASE     ,     cache_dir=model_args.cache_dir     ,     revision=model_args.model_revision     ,     use_auth_token=True if model_args.use_auth_token else None     ,     )
							else:
														logger.info('Training new model from scratch'				)
														_lowercase							:   Dict 							=   AutoModelForMaskedLM.from_config(SCREAMING_SNAKE_CASE				)

							model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE				)				)

							# Preprocessing the datasets.
							# First we tokenize all the texts.
							if training_args.do_train:
														_lowercase							:   Tuple 							=   datasets["""train"""].column_names
							else:
														_lowercase							:   Any 							=   datasets["""validation"""].column_names
							_lowercase							:   List[Any] 							=   """text""" if """text""" in column_names else column_names[0]

							_lowercase							:   List[str] 							=   """max_length""" if data_args.pad_to_max_length else False

							def tokenize_function(SCREAMING_SNAKE_CASE				):
														# Remove empty lines
														_lowercase							:   str 							=   [line for line in examples["""text"""] if len(SCREAMING_SNAKE_CASE				) > 0 and not line.isspace()]
														return tokenizer(examples['text']     ,     padding=SCREAMING_SNAKE_CASE     ,     truncation=SCREAMING_SNAKE_CASE     ,     max_length=data_args.max_seq_length				)

							_lowercase							:   List[str] 							=   datasets.map(
							    SCREAMING_SNAKE_CASE     ,     batched=SCREAMING_SNAKE_CASE     ,     num_proc=data_args.preprocessing_num_workers     ,     remove_columns=[text_column_name]     ,     load_from_cache_file=not data_args.overwrite_cache     ,     )

							# Add the chinese references if provided
							if data_args.train_ref_file is not None:
														_lowercase							:   List[Any] 							=   add_chinese_references(tokenized_datasets['train']     ,     data_args.train_ref_file				)
							if data_args.validation_ref_file is not None:
														_lowercase							:   Union[str, Any] 							=   add_chinese_references(
														    tokenized_datasets['validation']     ,     data_args.validation_ref_file				)
							# If we have ref files, need to avoid it removed by trainer
							_lowercase							:   Union[str, Any] 							=   data_args.train_ref_file or data_args.validation_ref_file
							if has_ref:
														_lowercase							:   Optional[Any] 							=   False

							# Data collator
							# This one will take care of randomly masking the tokens.
							_lowercase							:   List[str] 							=   DataCollatorForWholeWordMask(tokenizer=SCREAMING_SNAKE_CASE     ,     mlm_probability=data_args.mlm_probability				)

							# Initialize our Trainer
							_lowercase							:   int 							=   Trainer(
							    model=SCREAMING_SNAKE_CASE     ,     args=SCREAMING_SNAKE_CASE     ,     train_dataset=tokenized_datasets['train'] if training_args.do_train else None     ,     eval_dataset=tokenized_datasets['validation'] if training_args.do_eval else None     ,     tokenizer=SCREAMING_SNAKE_CASE     ,     data_collator=SCREAMING_SNAKE_CASE     ,     )

							# Training
							if training_args.do_train:
														if last_checkpoint is not None:
																					_lowercase							:   Tuple 							=   last_checkpoint
														elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path				):
																					_lowercase							:   Optional[int] 							=   model_args.model_name_or_path
														else:
																					_lowercase							:   Tuple 							=   None
														_lowercase							:   Optional[Any] 							=   trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE				)
														trainer.save_model()  # Saves the tokenizer too for easy upload

														_lowercase							:   Optional[Any] 							=   os.path.join(training_args.output_dir     ,     'train_results.txt'				)
														if trainer.is_world_process_zero():
																					with open(SCREAMING_SNAKE_CASE     ,     'w'				) as writer:
																												logger.info('***** Train results *****'				)
																												for key, value in sorted(train_result.metrics.items()				):
																																			logger.info(F"""  {key} = {value}"""				)
																																			writer.write(F"""{key} = {value}\n"""				)

            # Need to save the state, since Trainer.save_model saves only the tokenizer with the model
																					trainer.state.save_to_json(os.path.join(training_args.output_dir     ,     'trainer_state.json'				)				)

    # Evaluation
							_lowercase							:   Any 							=   {}
							if training_args.do_eval:
														logger.info('*** Evaluate ***'				)

														_lowercase							:   List[str] 							=   trainer.evaluate()

														_lowercase							:   Union[str, Any] 							=   math.exp(eval_output['eval_loss']				)
														_lowercase							:   List[Any] 							=   perplexity

														_lowercase							:   int 							=   os.path.join(training_args.output_dir     ,     'eval_results_mlm_wwm.txt'				)
														if trainer.is_world_process_zero():
																					with open(SCREAMING_SNAKE_CASE     ,     'w'				) as writer:
																												logger.info('***** Eval results *****'				)
																												for key, value in sorted(results.items()				):
																																			logger.info(F"""  {key} = {value}"""				)
																																			writer.write(F"""{key} = {value}\n"""				)

							return results






def    __magic_name__    (	SCREAMING_SNAKE_CASE				)     ->    Tuple:
							# For xla_spawn (TPUs)
							main()


if __name__ == "__main__":
							main()











"""simple docstring"""


import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


__magic_name__       :					str						=			logging.get_logger(__name__)  # pylint: disable=invalid-name






class 							lowercase__			(   __SCREAMING_SNAKE_CASE	):

			"""simple docstring"""







			def __init__(      self						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   _A						,   ):






									'''simple docstring'''







									super().__init__()

									if safety_checker is None:
															logger.warning(
															    f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"""
															    """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
															    """ results in services or applications open to the public. Both the diffusers team and Hugging Face"""
															    """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
															    """ it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
															    """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."""    )

									self.register_modules(
									    speech_model=_A						,   speech_processor=_A						,   vae=_A						,   text_encoder=_A						,   tokenizer=_A						,   unet=_A						,   scheduler=_A						,   feature_extractor=_A						,   )







			def   _a      (      self						,   _A = "auto"    ):






									'''simple docstring'''







									if slice_size == "auto":
															UpperCamelCase				:		List[Any]				   =			self.unet.config.attention_head_dim // 2
									self.unet.set_attention_slice(_A    )







			def   _a      (      self    ):






									'''simple docstring'''







									self.enable_attention_slicing(_A    )







			@torch.no_grad()
			def __call__(      self						,   _A						,   _A=1_6_0_0_0						,   _A = 5_1_2						,   _A = 5_1_2						,   _A = 5_0						,   _A = 7.5						,   _A = None						,   _A = 1						,   _A = 0.0						,   _A = None						,   _A = None						,   _A = "pil"						,   _A = True						,   _A = None						,   _A = 1						,   **_A						,   ):






									'''simple docstring'''







									UpperCamelCase				:		str				   =			self.speech_processor.feature_extractor(
									    _A						,   return_tensors="""pt"""						,   sampling_rate=_A    ).input_features.to(self.device    )
									UpperCamelCase				:		List[Any]				   =			self.speech_model.generate(_A						,   max_length=4_8_0_0_0_0    )

									UpperCamelCase				:		Optional[int]				   =			self.speech_processor.tokenizer.batch_decode(_A						,   skip_special_tokens=_A						,   normalize=_A    )[
									    0
									]

									if isinstance(_A						,   _A    ):
															UpperCamelCase				:		Tuple				   =			1
									elif isinstance(_A						,   _A    ):
															UpperCamelCase				:		List[Any]				   =			len(_A    )
									else:
															raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(_A    )}"""    )

									if height % 8 != 0 or width % 8 != 0:
															raise ValueError(f"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""    )

									if (callback_steps is None) or (
									    callback_steps is not None and (not isinstance(_A						,   _A    ) or callback_steps <= 0)
									):
															raise ValueError(
															    f"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
															    f""" {type(_A    )}."""    )

									# get prompt text embeddings
									UpperCamelCase				:		Dict				   =			self.tokenizer(
									    _A						,   padding="""max_length"""						,   max_length=self.tokenizer.model_max_length						,   return_tensors="""pt"""						,   )
									UpperCamelCase				:		Dict				   =			text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
															UpperCamelCase				:		Tuple				   =			self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]    )
															logger.warning(
															    """The following part of your input was truncated because CLIP can only handle sequences up to"""
															    f""" {self.tokenizer.model_max_length} tokens: {removed_text}"""    )
															UpperCamelCase				:		int				   =			text_input_ids[:, : self.tokenizer.model_max_length]
									UpperCamelCase				:		List[str]				   =			self.text_encoder(text_input_ids.to(self.device    )    )[0]

									# duplicate text embeddings for each generation per prompt, using mps friendly method
									UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase				:		Optional[Any]				   =			text_embeddings.shape
									UpperCamelCase				:		Optional[int]				   =			text_embeddings.repeat(1						,   _A						,   1    )
									UpperCamelCase				:		Union[str, Any]				   =			text_embeddings.view(bs_embed * num_images_per_prompt						,   _A						,   -1    )

									# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
									# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
									# corresponds to doing no classifier free guidance.
									UpperCamelCase				:		Optional[Any]				   =			guidance_scale > 1.0
									# get unconditional embeddings for classifier free guidance
									if do_classifier_free_guidance:
															UpperCamelCase				:		List[str]
															if negative_prompt is None:
																					UpperCamelCase				:		str				   =			[""""""] * batch_size
															elif type(_A    ) is not type(_A    ):
																					raise TypeError(
																					    f"""`negative_prompt` should be the same type to `prompt`, but got {type(_A    )} !="""
																					    f""" {type(_A    )}."""    )
															elif isinstance(_A						,   _A    ):
																					UpperCamelCase				:		Tuple				   =			[negative_prompt]
															elif batch_size != len(_A    ):
																					raise ValueError(
																					    f"""`negative_prompt`: {negative_prompt} has batch size {len(_A    )}, but `prompt`:"""
																					    f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
																					    """ the batch size of `prompt`."""    )
															else:
																					UpperCamelCase				:		Any				   =			negative_prompt

															UpperCamelCase				:		Optional[int]				   =			text_input_ids.shape[-1]
															UpperCamelCase				:		List[str]				   =			self.tokenizer(
															    _A						,   padding="""max_length"""						,   max_length=_A						,   truncation=_A						,   return_tensors="""pt"""						,   )
															UpperCamelCase				:		Optional[int]				   =			self.text_encoder(uncond_input.input_ids.to(self.device    )    )[0]

															# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
															UpperCamelCase				:		List[Any]				   =			uncond_embeddings.shape[1]
															UpperCamelCase				:		Dict				   =			uncond_embeddings.repeat(1						,   _A						,   1    )
															UpperCamelCase				:		Dict				   =			uncond_embeddings.view(batch_size * num_images_per_prompt						,   _A						,   -1    )

															# For classifier free guidance, we need to do two forward passes.
															# Here we concatenate the unconditional and text embeddings into a single batch
															# to avoid doing two forward passes
															UpperCamelCase				:		str				   =			torch.cat([uncond_embeddings, text_embeddings]    )

									# get the initial random noise unless the user supplied it

									# Unlike in other pipelines, latents need to be generated in the target device
									# for 1-to-1 results reproducibility with the CompVis implementation.
									# However this currently doesn't work in `mps`.
									UpperCamelCase				:		Any				   =			(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
									UpperCamelCase				:		int				   =			text_embeddings.dtype
									if latents is None:
															if self.device.type == "mps":
																					# randn does not exist on mps
																					UpperCamelCase				:		Tuple				   =			torch.randn(_A						,   generator=_A						,   device="""cpu"""						,   dtype=_A    ).to(
																					    self.device    )
															else:
																					UpperCamelCase				:		Any				   =			torch.randn(_A						,   generator=_A						,   device=self.device						,   dtype=_A    )
									else:
															if latents.shape != latents_shape:
																					raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""    )
															UpperCamelCase				:		Optional[Any]				   =			latents.to(self.device    )

									# set timesteps
									self.scheduler.set_timesteps(_A    )

									# Some schedulers like PNDM have timesteps as arrays
									# It's more optimized to move all timesteps to correct device beforehand
									UpperCamelCase				:		Tuple				   =			self.scheduler.timesteps.to(self.device    )

									# scale the initial noise by the standard deviation required by the scheduler
									UpperCamelCase				:		Any				   =			latents * self.scheduler.init_noise_sigma

									# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
									# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
									# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
									# and should be between [0, 1]
									UpperCamelCase				:		List[Any]				   =			"""eta""" in set(inspect.signature(self.scheduler.step    ).parameters.keys()    )
									UpperCamelCase				:		str				   =			{}
									if accepts_eta:
															UpperCamelCase				:		Union[str, Any]				   =			eta

									for i, t in enumerate(self.progress_bar(_A    )    ):
															# expand the latents if we are doing classifier free guidance
															UpperCamelCase				:		Union[str, Any]				   =			torch.cat([latents] * 2    ) if do_classifier_free_guidance else latents
															UpperCamelCase				:		str				   =			self.scheduler.scale_model_input(_A						,   _A    )

															# predict the noise residual
															UpperCamelCase				:		Optional[Any]				   =			self.unet(_A						,   _A						,   encoder_hidden_states=_A    ).sample

															# perform guidance
															if do_classifier_free_guidance:
																					UpperCamelCase   ,						UpperCamelCase				:		str				   =			noise_pred.chunk(2    )
																					UpperCamelCase				:		List[str]				   =			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

															# compute the previous noisy sample x_t -> x_t-1
															UpperCamelCase				:		Any				   =			self.scheduler.step(_A						,   _A						,   _A						,   **_A    ).prev_sample

															# call the callback, if provided
															if callback is not None and i % callback_steps == 0:
																					callback(_A						,   _A						,   _A    )

									UpperCamelCase				:		Optional[Any]				   =			1 / 0.1_82_15 * latents
									UpperCamelCase				:		Union[str, Any]				   =			self.vae.decode(_A    ).sample

									UpperCamelCase				:		List[Any]				   =			(image / 2 + 0.5).clamp(0						,   1    )

									# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
									UpperCamelCase				:		Dict				   =			image.cpu().permute(0						,   2						,   3						,   1    ).float().numpy()

									if output_type == "pil":
															UpperCamelCase				:		Optional[Any]				   =			self.numpy_to_pil(_A    )

									if not return_dict:
															return image

									return StableDiffusionPipelineOutput(images=_A						,   nsfw_content_detected=_A    )



