





"""simple docstring"""




import argparse
import gc
import os
import threading

import evaluate
import psutil
import torch
from datasets import load_dataset
from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig
from torch.utils.data import DataLoader
from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    get_linear_schedule_with_warmup,
    set_seed,
)

from accelerate import Accelerator, DistributedType, FullyShardedDataParallelPlugin


########################################################################
# This is a fully working simple example to use Accelerate
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#   - FSDP
#
# This example also demonstrates the checkpointing and sharding capabilities
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


UpperCamelCase_           =16
UpperCamelCase_           =32





def        a_				(							_lowercase   ):
						return int(x / 2**20   )




class  _a						:






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




										'''simple docstring'''



										gc.collect()
										torch.cuda.empty_cache()
										torch.cuda.reset_max_memory_allocated()  # reset the peak gauge to zero
										_UpperCamelCase			:					Dict     =    torch.cuda.memory_allocated()
										_UpperCamelCase			:					List[Any]     =    psutil.Process()

										_UpperCamelCase			:					List[Any]     =    self.cpu_mem_used()
										_UpperCamelCase			:					Any     =    True
										_UpperCamelCase			:					Optional[int]     =    threading.Thread(target=self.peak_monitor_func							)
										_UpperCamelCase			:					Tuple     =    True
										peak_monitor_thread.start()
										return self






				def 				snake_case	( self		:    Optional[int]							)	->      Union[str, Any]:




										'''simple docstring'''



										return self.process.memory_info().rss






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




										'''simple docstring'''



										_UpperCamelCase			:					Tuple     =    -1

										while True:
																_UpperCamelCase			:					List[Any]     =    max(self.cpu_mem_used(), self.cpu_peak							)

																# can't sleep or will not catch the peak right (this comment is here on purpose)
																# time.sleep(0.001) # 1msec

																if not self.peak_monitoring:
																						break






				def __exit__( self		:    Dict, *lowerCAmelCase__		:    Dict							)	->      List[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					Tuple     =    False

										gc.collect()
										torch.cuda.empty_cache()
										_UpperCamelCase			:					List[Any]     =    torch.cuda.memory_allocated()
										_UpperCamelCase			:					List[Any]     =    torch.cuda.max_memory_allocated()
										_UpperCamelCase			:					Tuple     =    bamb(self.end - self.begin							)
										_UpperCamelCase			:					Tuple     =    bamb(self.peak - self.begin							)

										_UpperCamelCase			:					Union[str, Any]     =    self.cpu_mem_used()
										_UpperCamelCase			:					Tuple     =    bamb(self.cpu_end - self.cpu_begin							)
										_UpperCamelCase			:					Tuple     =    bamb(self.cpu_peak - self.cpu_begin							)
										# print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")


# For testing only
if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1":
						from accelerate.test_utils.training import mocked_dataloaders

						UpperCamelCase_           =mocked_dataloaders  # noqa: F811





def        a_				(							_lowercase       ,						_lowercase   ):
						# For testing only
						if os.environ.get('''TESTING_MOCKED_DATALOADERS'''       ,						_lowercase   ) == "1":
												_UpperCamelCase			:					int     =    2

						# New Code #
						# Pass the advanced FSDP settings not part of the accelerate config by creating fsdp_plugin
						_UpperCamelCase			:					Tuple     =    FullyShardedDataParallelPlugin(
						    state_dict_config=FullStateDictConfig(offload_to_cpu=_lowercase       ,						ranka_only=_lowercase   )       ,						optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=_lowercase       ,						ranka_only=_lowercase   )       ,						)

						# Initialize accelerator
						if args.with_tracking:
												_UpperCamelCase			:					int     =    Accelerator(
												    cpu=args.cpu       ,						mixed_precision=args.mixed_precision       ,						log_with='''wandb'''       ,						project_dir=args.logging_dir       ,						fsdp_plugin=_lowercase       ,						)
						else:
												_UpperCamelCase			:					str     =    Accelerator(fsdp_plugin=_lowercase   )
						accelerator.print(accelerator.distributed_type   )

						if hasattr(args.checkpointing_steps       ,						'''isdigit'''   ):
												if args.checkpointing_steps == "epoch":
																		_UpperCamelCase			:					Union[str, Any]     =    args.checkpointing_steps
												elif args.checkpointing_steps.isdigit():
																		_UpperCamelCase			:					List[Any]     =    int(args.checkpointing_steps   )
												else:
																		raise ValueError(
																		    F"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."""   )
						else:
												_UpperCamelCase			:					List[str]     =    None
						# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
						_UpperCamelCase			:					List[str]     =    config['''lr''']
						_UpperCamelCase			:					Optional[int]     =    int(config['''num_epochs''']   )
						_UpperCamelCase			:					Dict     =    int(config['''seed''']   )
						_UpperCamelCase			:					List[str]     =    int(config['''batch_size''']   )

						# We need to initialize the trackers we use, and also store our configuration
						if args.with_tracking:
												_UpperCamelCase			:					List[Any]     =    vars(_lowercase   )
												accelerator.init_trackers('''fsdp_glue_no_trainer'''       ,						_lowercase   )

						_UpperCamelCase			:					Optional[int]     =    AutoTokenizer.from_pretrained(args.model_name_or_path   )
						_UpperCamelCase			:					int     =    load_dataset('''glue'''       ,						'''mrpc'''   )
						_UpperCamelCase			:					Optional[Any]     =    evaluate.load('''glue'''       ,						'''mrpc'''   )

						def tokenize_function(_lowercase   ):
												# max_length=None => use the model max length (it's actually the default)
												_UpperCamelCase			:					Optional[Any]     =    tokenizer(examples['''sentence1''']       ,						examples['''sentence2''']       ,						truncation=_lowercase       ,						max_length=_lowercase   )
												return outputs

						# Apply the method we just defined to all the examples in all the splits of the dataset
						# starting with the main process first:
						with accelerator.main_process_first():
												_UpperCamelCase			:					Any     =    datasets.map(
												    _lowercase       ,						batched=_lowercase       ,						remove_columns=['''idx''', '''sentence1''', '''sentence2''']       ,						)

						# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
						# transformers library
						_UpperCamelCase			:					Optional[int]     =    tokenized_datasets.rename_column('''label'''       ,						'''labels'''   )

						# If the batch size is too big we use gradient accumulation
						_UpperCamelCase			:					Optional[Any]     =    1
						if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
												_UpperCamelCase			:					Optional[int]     =    batch_size // MAX_GPU_BATCH_SIZE
												_UpperCamelCase			:					str     =    MAX_GPU_BATCH_SIZE

						def collate_fn(_lowercase   ):
												# On TPU it's best to pad everything to the same length or training will be very slow.
												_UpperCamelCase			:					Optional[Any]     =    128 if accelerator.distributed_type == DistributedType.TPU else None
												# When using mixed precision we want round multiples of 8/16
												if accelerator.mixed_precision == "fp8":
																		_UpperCamelCase			:					Optional[Any]     =    16
												elif accelerator.mixed_precision != "no":
																		_UpperCamelCase			:					Union[str, Any]     =    8
												else:
																		_UpperCamelCase			:					Dict     =    None

												return tokenizer.pad(
												    _lowercase       ,						padding='''longest'''       ,						max_length=_lowercase       ,						pad_to_multiple_of=_lowercase       ,						return_tensors='''pt'''       ,						)

						# Instantiate dataloaders.
						_UpperCamelCase			:					Optional[int]     =    DataLoader(
						    tokenized_datasets['''train''']       ,						shuffle=_lowercase       ,						collate_fn=_lowercase       ,						batch_size=_lowercase   )
						_UpperCamelCase			:					Any     =    DataLoader(
						    tokenized_datasets['''validation''']       ,						shuffle=_lowercase       ,						collate_fn=_lowercase       ,						batch_size=_lowercase   )

						set_seed(_lowercase   )

						# Instantiate the model (we build the model here so that the seed also control new weights initialization)
						_UpperCamelCase			:					List[str]     =    AutoModelForSequenceClassification.from_pretrained(
						    args.model_name_or_path       ,						return_dict=_lowercase       ,						low_cpu_mem_usage=_lowercase   )

						# New Code #
						# For FSDP feature, it is highly recommended and efficient to prepare the model before creating optimizer
						_UpperCamelCase			:					List[str]     =    accelerator.prepare(_lowercase   )
						accelerator.print(_lowercase   )

						# Instantiate optimizer
						# New Code #
						# For FSDP feature, at present it doesn't support multiple parameter groups,
						# so we need to create a single parameter group for the whole model
						_UpperCamelCase			:					Optional[int]     =    torch.optim.AdamW(params=model.parameters()       ,						lr=_lowercase       ,						weight_decay=2E-4   )

						# Instantiate scheduler
						_UpperCamelCase			:					str     =    get_linear_schedule_with_warmup(
						    optimizer=_lowercase       ,						num_warmup_steps=10       ,						num_training_steps=(len(_lowercase   ) * num_epochs) // gradient_accumulation_steps       ,						)

						# New Code #
						# For FSDP feature, prepare everything except the model as we have already prepared the model
						# before creating the optimizer
						# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
						# prepare method.
						_UpperCamelCase   ,							_UpperCamelCase   ,							_UpperCamelCase   ,							_UpperCamelCase			:					Dict     =    accelerator.prepare(
						    _lowercase       ,						_lowercase       ,						_lowercase       ,						_lowercase   )

						_UpperCamelCase			:					Tuple     =    0

						# Potentially load in the weights and states from a previous save
						if args.resume_from_checkpoint:
												if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
																		accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}"""   )
																		accelerator.load_state(args.resume_from_checkpoint   )
																		_UpperCamelCase			:					List[Any]     =    os.path.basename(args.resume_from_checkpoint   )
												else:
																		# Get the most recent checkpoint
																		_UpperCamelCase			:					Optional[int]     =    [f.name for f in os.scandir(os.getcwd()   ) if f.is_dir()]
																		dirs.sort(key=os.path.getctime   )
																		_UpperCamelCase			:					Optional[Any]     =    dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
												# Extract `epoch_{i}` or `step_{i}`
												_UpperCamelCase			:					List[Any]     =    os.path.splitext(_lowercase   )[0]

												if "epoch" in training_difference:
																		num_epochs -= int(training_difference.replace('''epoch_'''       ,						''''''   )   )
																		_UpperCamelCase			:					str     =    None
												else:
																		_UpperCamelCase			:					List[str]     =    int(training_difference.replace('''step_'''       ,						''''''   )   )
																		num_epochs -= resume_step // len(_lowercase   )
																		# If resuming by step, we also need to know exactly how far into the DataLoader we went
																		_UpperCamelCase			:					Dict     =    (num_epochs * len(_lowercase   )) - resume_step

    # Now we train the model
						for epoch in range(_lowercase   ):
												# New Code #
												# context manager to track the peak memory usage during the training epoch
												with TorchTracemalloc() as tracemalloc:
																		model.train()
																		if args.with_tracking:
																								_UpperCamelCase			:					Dict     =    0
																		for step, batch in enumerate(_lowercase   ):
																								# We need to skip steps until we reach the resumed step
																								if args.resume_from_checkpoint and epoch == 0:
																														if resume_step is not None and step < resume_step:
																																				pass
                # We could avoid this line since we set the accelerator with `device_placement=True`.
																								batch.to(accelerator.device   )
																								_UpperCamelCase			:					List[Any]     =    model(**_lowercase   )
																								_UpperCamelCase			:					Tuple     =    outputs.loss
																								_UpperCamelCase			:					Union[str, Any]     =    loss / gradient_accumulation_steps
																								# We keep track of the loss at each epoch
																								if args.with_tracking:
																														total_loss += loss.detach().float()
																								accelerator.backward(_lowercase   )
																								if step % gradient_accumulation_steps == 0:
																														optimizer.step()
																														lr_scheduler.step()
																														optimizer.zero_grad()
																														# accelerator.print(lr_scheduler.get_lr())

																								overall_step += 1

																								if isinstance(_lowercase       ,						_lowercase   ):
																														_UpperCamelCase			:					Any     =    F"""step_{overall_step}"""
																														if overall_step % checkpointing_steps == 0:
																																				if args.output_dir is not None:
																																										_UpperCamelCase			:					List[Any]     =    os.path.join(args.output_dir       ,						_lowercase   )
																																				accelerator.save_state(_lowercase   )
        # New Code #
        # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
												accelerator.print('''Memory before entering the train : {}'''.format(bamb(tracemalloc.begin   )   )   )
												accelerator.print('''Memory consumed at the end of the train (end-begin): {}'''.format(tracemalloc.used   )   )
												accelerator.print('''Peak Memory consumed during the train (max-begin): {}'''.format(tracemalloc.peaked   )   )
												accelerator.print(
												    '''Total Peak Memory consumed during the train (max): {}'''.format(
												        tracemalloc.peaked + bamb(tracemalloc.begin   )   )   )
												# Logging the peak memory usage of the GPU to the tracker
												if args.with_tracking:
																		accelerator.log(
																		    {
																		        '''train_total_peak_memory''': tracemalloc.peaked + bamb(tracemalloc.begin   ),
																		    }       ,						step=_lowercase       ,						)

												# New Code #
												# context manager to track the peak memory usage during the evaluation
												with TorchTracemalloc() as tracemalloc:
																		model.eval()
																		for step, batch in enumerate(_lowercase   ):
																								# We could avoid this line since we set the accelerator with `device_placement=True`.
																								batch.to(accelerator.device   )
																								with torch.no_grad():
																														_UpperCamelCase			:					Dict     =    model(**_lowercase   )
																								_UpperCamelCase			:					List[Any]     =    outputs.logits.argmax(dim=-1   )
																								_UpperCamelCase   ,							_UpperCamelCase			:					Optional[int]     =    accelerator.gather_for_metrics((predictions, batch['''labels'''])   )
																								metric.add_batch(
																								    predictions=_lowercase       ,						references=_lowercase       ,						)

																		_UpperCamelCase			:					int     =    metric.compute()
																		# Use accelerator.print to print only on the main process.
																		accelerator.print(F"""epoch {epoch}:"""       ,						_lowercase   )
																		if args.with_tracking:
																								accelerator.log(
																								    {
																								        '''accuracy''': eval_metric['''accuracy'''],
																								        '''f1''': eval_metric['''f1'''],
																								        '''train_loss''': total_loss.item() / len(_lowercase   ),
																								    }       ,						step=_lowercase       ,						)

																		if checkpointing_steps == "epoch":
																								_UpperCamelCase			:					int     =    F"""epoch_{epoch}"""
																								if args.output_dir is not None:
																														_UpperCamelCase			:					Optional[Any]     =    os.path.join(args.output_dir       ,						_lowercase   )
																								accelerator.save_state(_lowercase   )
        # New Code #
        # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
												accelerator.print('''Memory before entering the eval : {}'''.format(bamb(tracemalloc.begin   )   )   )
												accelerator.print('''Memory consumed at the end of the eval (end-begin): {}'''.format(tracemalloc.used   )   )
												accelerator.print('''Peak Memory consumed during the eval (max-begin): {}'''.format(tracemalloc.peaked   )   )
												accelerator.print(
												    '''Total Peak Memory consumed during the eval (max): {}'''.format(tracemalloc.peaked + bamb(tracemalloc.begin   )   )   )
												# Logging the peak memory usage of the GPU to the tracker
												if args.with_tracking:
																		accelerator.log(
																		    {
																		        '''eval_total_peak_memory''': tracemalloc.peaked + bamb(tracemalloc.begin   ),
																		    }       ,						step=_lowercase       ,						)

						if args.with_tracking:
												accelerator.end_training()





def        a_				(							):
						_UpperCamelCase			:					Optional[Any]     =    argparse.ArgumentParser(description='''Simple example of training script.'''   )
						parser.add_argument(
						    '''--mixed_precision'''       ,						type=_lowercase       ,						default=_lowercase       ,						choices=['''no''', '''fp16''', '''bf16''', '''fp8''']       ,						help='''Whether to use mixed precision. Choose'''
						    '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
						    '''and an Nvidia Ampere GPU.'''       ,						)
						parser.add_argument('''--cpu'''       ,						action='''store_true'''       ,						help='''If passed, will train on the CPU.'''   )
						parser.add_argument(
						    '''--checkpointing_steps'''       ,						type=_lowercase       ,						default=_lowercase       ,						help='''Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.'''       ,						)
						parser.add_argument(
						    '''--resume_from_checkpoint'''       ,						type=_lowercase       ,						default=_lowercase       ,						help='''If the training should continue from a checkpoint folder.'''       ,						)
						parser.add_argument(
						    '''--with_tracking'''       ,						action='''store_true'''       ,						help='''Whether to load in all available experiment trackers from the environment and use them for logging.'''       ,						)
						parser.add_argument(
						    '''--output_dir'''       ,						type=_lowercase       ,						default='''.'''       ,						help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.'''       ,						)
						parser.add_argument(
						    '''--logging_dir'''       ,						type=_lowercase       ,						default='''logs'''       ,						help='''Location on where to store experiment tracking logs`'''       ,						)
						parser.add_argument(
						    '''--model_name_or_path'''       ,						type=_lowercase       ,						help='''Path to pretrained model or model identifier from huggingface.co/models.'''       ,						required=_lowercase       ,						)
						_UpperCamelCase			:					List[str]     =    parser.parse_args()
						_UpperCamelCase			:					str     =    {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
						training_function(_lowercase       ,						_lowercase   )


if __name__ == "__main__":
						main()










"""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  _a						(      unittest.TestCase				):






				def 				snake_case	( self		:    Any							)	->      Any:




										'''simple docstring'''



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






				@property
				def 				snake_case	( self		:    Optional[int]							)	->      Tuple:




										'''simple docstring'''



										_UpperCamelCase			:					List[str]     =    1
										_UpperCamelCase			:					Union[str, Any]     =    3
										_UpperCamelCase			:					Tuple     =    (3_2, 3_2)

										_UpperCamelCase			:					Any     =    floats_tensor((batch_size, num_channels) + sizes, rng=random.Random(0							)							).to(lowerCAmelCase__							)
										return image






				@property
				def 				snake_case	( self		:    Tuple							)	->      Union[str, Any]:




										'''simple docstring'''



										torch.manual_seed(0							)
										_UpperCamelCase			:					Dict     =    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 				snake_case	( self		:    Dict							)	->      List[Any]:




										'''simple docstring'''



										torch.manual_seed(0							)
										_UpperCamelCase			:					List[str]     =    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 				snake_case	( self		:    List[str]							)	->      Tuple:




										'''simple docstring'''



										torch.manual_seed(0							)
										_UpperCamelCase			:					Any     =    CLIPTextConfig(
										    bos_token_id=0, eos_token_id=2, hidden_size=3_2, intermediate_size=3_7, layer_norm_eps=1e-0_5, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, )
										return CLIPTextModel(lowerCAmelCase__							)






				@property
				def 				snake_case	( self		:    Dict							)	->      str:




										'''simple docstring'''



										def extract(*lowerCAmelCase__		:    int, **lowerCAmelCase__		:    int							):




																class  _a						:






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




																										'''simple docstring'''



																										_UpperCamelCase			:					Optional[int]     =    torch.ones([0]							)






																				def 				snake_case	( self		:    List[Any], lowerCAmelCase__		:    List[str]							)	->      Tuple:




																										'''simple docstring'''



																										self.pixel_values.to(lowerCAmelCase__							)
																										return self

																return Out()

										return extract






				def 				snake_case	( self		:    List[str]							)	->      int:




										'''simple docstring'''



										_UpperCamelCase			:					Any     =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
										_UpperCamelCase			:					Optional[Any]     =    self.dummy_cond_unet
										_UpperCamelCase			:					int     =    DDIMScheduler(
										    beta_start=0.00_085, beta_end=0.012, beta_schedule='''scaled_linear''', clip_sample=lowerCAmelCase__, set_alpha_to_one=lowerCAmelCase__, )

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

										# make sure here that pndm scheduler skips prk
										_UpperCamelCase			:					Tuple     =    StableDiffusionPipeline(
										    unet=lowerCAmelCase__, scheduler=lowerCAmelCase__, vae=lowerCAmelCase__, text_encoder=lowerCAmelCase__, tokenizer=lowerCAmelCase__, safety_checker=lowerCAmelCase__, feature_extractor=self.dummy_extractor, )
										_UpperCamelCase			:					str     =    sd_pipe.to(lowerCAmelCase__							)
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					Optional[Any]     =    '''A painting of a squirrel eating a burger'''

										_UpperCamelCase			:					Any     =    torch.Generator(device=lowerCAmelCase__							).manual_seed(0							)
										_UpperCamelCase			:					List[Any]     =    sd_pipe([prompt], generator=lowerCAmelCase__, guidance_scale=6.0, num_inference_steps=2, output_type='''np'''							)
										_UpperCamelCase			:					Optional[Any]     =    output.images

										_UpperCamelCase			:					str     =    torch.Generator(device=lowerCAmelCase__							).manual_seed(0							)
										_UpperCamelCase			:					List[Any]     =    sd_pipe(
										    [prompt], generator=lowerCAmelCase__, guidance_scale=6.0, num_inference_steps=2, output_type='''np''', return_dict=lowerCAmelCase__, )[0]

										_UpperCamelCase			:					List[Any]     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					Tuple     =    image_from_tuple[0, -3:, -3:, -1]

										assert image.shape == (1, 6_4, 6_4, 3)
										_UpperCamelCase			:					Tuple     =    np.array([0.5_753, 0.6_114, 0.5_001, 0.5_034, 0.5_470, 0.4_729, 0.4_971, 0.4_867, 0.4_867]							)

										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 				snake_case	( self		:    str							)	->      str:




										'''simple docstring'''



										_UpperCamelCase			:					Optional[Any]     =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
										_UpperCamelCase			:					Optional[int]     =    self.dummy_cond_unet
										_UpperCamelCase			:					List[str]     =    PNDMScheduler(skip_prk_steps=lowerCAmelCase__							)
										_UpperCamelCase			:					int     =    self.dummy_vae
										_UpperCamelCase			:					Optional[Any]     =    self.dummy_text_encoder
										_UpperCamelCase			:					Union[str, Any]     =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)

										# make sure here that pndm scheduler skips prk
										_UpperCamelCase			:					int     =    StableDiffusionPipeline(
										    unet=lowerCAmelCase__, scheduler=lowerCAmelCase__, vae=lowerCAmelCase__, text_encoder=lowerCAmelCase__, tokenizer=lowerCAmelCase__, safety_checker=lowerCAmelCase__, feature_extractor=self.dummy_extractor, )
										_UpperCamelCase			:					List[str]     =    sd_pipe.to(lowerCAmelCase__							)
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					Tuple     =    '''A painting of a squirrel eating a burger'''
										_UpperCamelCase			:					Union[str, Any]     =    torch.Generator(device=lowerCAmelCase__							).manual_seed(0							)
										_UpperCamelCase			:					str     =    sd_pipe([prompt], generator=lowerCAmelCase__, guidance_scale=6.0, num_inference_steps=2, output_type='''np'''							)

										_UpperCamelCase			:					Dict     =    output.images

										_UpperCamelCase			:					List[Any]     =    torch.Generator(device=lowerCAmelCase__							).manual_seed(0							)
										_UpperCamelCase			:					int     =    sd_pipe(
										    [prompt], generator=lowerCAmelCase__, guidance_scale=6.0, num_inference_steps=2, output_type='''np''', return_dict=lowerCAmelCase__, )[0]

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

										assert image.shape == (1, 6_4, 6_4, 3)
										_UpperCamelCase			:					Optional[Any]     =    np.array([0.5_122, 0.5_712, 0.4_825, 0.5_053, 0.5_646, 0.4_769, 0.5_179, 0.4_894, 0.4_994]							)

										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 				snake_case	( self		:    List[str]							)	->      int:




										'''simple docstring'''



										_UpperCamelCase			:					int     =    StableDiffusionPipeline.from_pretrained(
										    '''hf-internal-testing/tiny-stable-diffusion-lms-pipe''', safety_checker=lowerCAmelCase__							)
										assert isinstance(lowerCAmelCase__, lowerCAmelCase__							)
										assert isinstance(pipe.scheduler, lowerCAmelCase__							)
										assert pipe.safety_checker is None

										_UpperCamelCase			:					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(lowerCAmelCase__							)
																_UpperCamelCase			:					List[str]     =    StableDiffusionPipeline.from_pretrained(lowerCAmelCase__							)

										# sanity check that the pipeline still works
										assert pipe.safety_checker is None
										_UpperCamelCase			:					int     =    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 				snake_case	( self		:    Any							)	->      List[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					Any     =    self.dummy_cond_unet
										_UpperCamelCase			:					Union[str, Any]     =    PNDMScheduler(skip_prk_steps=lowerCAmelCase__							)
										_UpperCamelCase			:					int     =    self.dummy_vae
										_UpperCamelCase			:					List[Any]     =    self.dummy_text_encoder
										_UpperCamelCase			:					Union[str, Any]     =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)

										# put models in fp16
										_UpperCamelCase			:					int     =    unet.half()
										_UpperCamelCase			:					Any     =    vae.half()
										_UpperCamelCase			:					List[Any]     =    bert.half()

										# make sure here that pndm scheduler skips prk
										_UpperCamelCase			:					Optional[int]     =    StableDiffusionPipeline(
										    unet=lowerCAmelCase__, scheduler=lowerCAmelCase__, vae=lowerCAmelCase__, text_encoder=lowerCAmelCase__, tokenizer=lowerCAmelCase__, safety_checker=lowerCAmelCase__, feature_extractor=self.dummy_extractor, )
										_UpperCamelCase			:					Optional[int]     =    sd_pipe.to(lowerCAmelCase__							)
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					Optional[Any]     =    '''A painting of a squirrel eating a burger'''
										_UpperCamelCase			:					List[str]     =    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  _a						(      unittest.TestCase				):






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




										'''simple docstring'''



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






				def 				snake_case	( self		:    int							)	->      Any:




										'''simple docstring'''



										_UpperCamelCase			:					int     =    '''cuda'''
										_UpperCamelCase			:					List[Any]     =    StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''							)
										_UpperCamelCase			:					int     =    pipe.to(lowerCAmelCase__							)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					str     =    '''a photo of a cat'''
										_UpperCamelCase			:					Tuple     =    {
										    '''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,
										}

										_UpperCamelCase			:					Optional[int]     =    3
										_UpperCamelCase			:					int     =    7

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

										_UpperCamelCase			:					Optional[Any]     =    output.images
										_UpperCamelCase			:					Tuple     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					List[str]     =    [
										    0.34_673_113,
										    0.38_492_733,
										    0.37_597_352,
										    0.34_086_335,
										    0.35_650_748,
										    0.35_579_205,
										    0.3_384_763,
										    0.34_340_236,
										    0.3_573_271,
										]

										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(lowerCAmelCase__							)
										_UpperCamelCase			:					Optional[int]     =    pipe(
										    [prompt], generator=lowerCAmelCase__, guidance_scale=lowerCAmelCase__, num_inference_steps=5_0, output_type='''np''', width=5_1_2, height=5_1_2, **lowerCAmelCase__, )

										_UpperCamelCase			:					Dict     =    output.images
										_UpperCamelCase			:					int     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					Optional[int]     =    [
										    0.41_887_826,
										    0.37_728_766,
										    0.30_138_272,
										    0.41_416_335,
										    0.41_664_985,
										    0.36_283_392,
										    0.36_191_246,
										    0.43_364_465,
										    0.43_001_732,
										]

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

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






				def 				snake_case	( self		:    Tuple							)	->      Tuple:




										'''simple docstring'''



										_UpperCamelCase			:					str     =    '''cuda'''
										_UpperCamelCase			:					str     =    StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''							)
										_UpperCamelCase			:					List[Any]     =    pipe.to(lowerCAmelCase__							)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					int     =    '''an image of a crowded boulevard, realistic, 4k'''
										_UpperCamelCase			:					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,
										}

										_UpperCamelCase			:					Dict     =    9
										_UpperCamelCase			:					Optional[Any]     =    7

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

										_UpperCamelCase			:					List[str]     =    output.images
										_UpperCamelCase			:					Union[str, Any]     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					Dict     =    [
										    0.43_497_998,
										    0.91_814_065,
										    0.7_540_739,
										    0.55_580_205,
										    0.8_467_265,
										    0.5_389_691,
										    0.62_574_506,
										    0.58_897_763,
										    0.50_926_757,
										]

										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(lowerCAmelCase__							)
										_UpperCamelCase			:					int     =    pipe(
										    [prompt], generator=lowerCAmelCase__, guidance_scale=lowerCAmelCase__, num_inference_steps=5_0, output_type='''np''', width=5_1_2, height=5_1_2, **lowerCAmelCase__, )

										_UpperCamelCase			:					int     =    output.images
										_UpperCamelCase			:					Optional[int]     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					List[Any]     =    [
										    0.3_089_719,
										    0.30_500_144,
										    0.29_016_042,
										    0.30_630_964,
										    0.325_687,
										    0.29_419_225,
										    0.2_908_091,
										    0.28_723_598,
										    0.27_696_294,
										]

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

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






				def 				snake_case	( self		:    str							)	->      str:




										'''simple docstring'''



										_UpperCamelCase			:					int     =    '''cuda'''
										_UpperCamelCase			:					str     =    StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''							)
										_UpperCamelCase			:					Union[str, Any]     =    pipe.to(lowerCAmelCase__							)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					Optional[int]     =    '''a castle next to a river'''
										_UpperCamelCase			:					Optional[int]     =    {
										    '''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,
										}

										_UpperCamelCase			:					Tuple     =    4_8
										_UpperCamelCase			:					List[str]     =    7

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

										_UpperCamelCase			:					Optional[Any]     =    output.images
										_UpperCamelCase			:					Optional[Any]     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					str     =    [
										    0.75_163_555,
										    0.76_037_145,
										    0.61_785,
										    0.9_189_673,
										    0.8_627_701,
										    0.85_189_694,
										    0.8_512_813,
										    0.87_012_076,
										    0.8_312_857,
										]

										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(lowerCAmelCase__							)
										_UpperCamelCase			:					Optional[int]     =    pipe(
										    [prompt], generator=lowerCAmelCase__, guidance_scale=lowerCAmelCase__, num_inference_steps=5_0, output_type='''np''', width=5_1_2, height=5_1_2, **lowerCAmelCase__, )

										_UpperCamelCase			:					int     =    output.images
										_UpperCamelCase			:					List[str]     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					Dict     =    [
										    0.73_553_365,
										    0.7_537_271,
										    0.74_341_905,
										    0.66_480_356,
										    0.6_472_925,
										    0.63_039_416,
										    0.64_812_905,
										    0.6_749_717,
										    0.6_517_102,
										]

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

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






				def 				snake_case	( self		:    Union[str, Any]							)	->      Optional[int]:




										'''simple docstring'''



										_UpperCamelCase			:					Dict     =    '''cuda'''
										_UpperCamelCase			:					List[str]     =    StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''', torch_dtype=torch.floataa							)
										_UpperCamelCase			:					int     =    pipe.to(lowerCAmelCase__							)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

										_UpperCamelCase			:					List[Any]     =    '''a photo of a cat'''
										_UpperCamelCase			:					str     =    {
										    '''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,
										}

										_UpperCamelCase			:					Tuple     =    3
										_UpperCamelCase			:					List[str]     =    7

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

										_UpperCamelCase			:					Union[str, Any]     =    output.images
										_UpperCamelCase			:					Union[str, Any]     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					List[Any]     =    [
										    0.34_887_695,
										    0.3_876_953,
										    0.375,
										    0.34_423_828,
										    0.3_581_543,
										    0.35_717_773,
										    0.3_383_789,
										    0.34_570_312,
										    0.359_375,
										]

										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(lowerCAmelCase__							)
										_UpperCamelCase			:					Optional[int]     =    pipe(
										    [prompt], generator=lowerCAmelCase__, guidance_scale=lowerCAmelCase__, num_inference_steps=5_0, output_type='''np''', width=5_1_2, height=5_1_2, **lowerCAmelCase__, )

										_UpperCamelCase			:					Tuple     =    output.images
										_UpperCamelCase			:					int     =    image[0, -3:, -3:, -1]
										_UpperCamelCase			:					Optional[Any]     =    [
										    0.42_285_156,
										    0.36_914_062,
										    0.29_077_148,
										    0.42_041_016,
										    0.41_918_945,
										    0.35_498_047,
										    0.3_618_164,
										    0.4_423_828,
										    0.43_115_234,
										]

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

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



