
'''simple docstring'''







import copy
import logging
import random

import joblib
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AdamW, GPTaLMHeadModel, get_linear_schedule_with_warmup


lowerCAmelCase_      =   logging.getLogger(__name__)







def   lowerCAmelCase(  a__    :  Optional[Any]      ):







       '''simple docstring'''






       random.seed(a__      )
       np.random.seed(a__      )
       torch.manual_seed(a__      )
       torch.cuda.manual_seed_all(a__      )







def   lowerCAmelCase(  a__    :  List[str]      , a__    :  Tuple      , a__    :  int      ):







       '''simple docstring'''






       model.eval()
       lowerCamelCase__				   =      next(model.parameters()      ).device
       lowerCamelCase__				   =      1
       lowerCamelCase__				   =      torch.zeros((eval_batch_size, context_len)      , dtype=torch.long      , device=a__      )
       lowerCamelCase__				   =      DataLoader(a__      , shuffle=a__      , batch_size=a__      )
       lowerCamelCase__				   =      torch.zeros(1      , device=a__      )
       lowerCamelCase__				   =      0
       for batch in eval_dataloader:
              batch.to(a__      )
              # pad
              context.zero_()
              for i in range(a__      ):
                     lowerCamelCase__				   =      batch[i]
              lowerCamelCase__				   =      model(a__      , labels=a__      )
              eval_loss += outputs[0].sum().item()
              nb_eval_examples += batch.size(0      )
       lowerCamelCase__				   =      eval_loss / nb_eval_examples
       lowerCamelCase__				   =      torch.exp(a__      )
       model.train()
       return perplexity







def   lowerCAmelCase(  a__    :  Any="gpt2"      ):







       '''simple docstring'''






       lowerCamelCase__				   =      GPTaLMHeadModel.from_pretrained(a__      , output_hidden_states=a__      )
       torch.save(model.state_dict()      , model_name + "local.pt"      )
       return model







def   lowerCAmelCase(  a__    :  List[str]      , a__    :  Dict      , a__    :  Optional[int]      ):







       '''simple docstring'''






       lowerCamelCase__				   =      copy.deepcopy(a__      )
       model.to(a__      )

       lowerCamelCase__				   =      ['''bias''', '''LayerNorm.weight''']
       lowerCamelCase__				   =      [
           {
               '''params''': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay      )],
               '''weight_decay''': 0.0,
           },
           {'''params''': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay      )], '''weight_decay''': 0.0},
       ]
       lowerCamelCase__				   =      AdamW(a__      , lr=5E-5      , eps=1E-8      )
       lowerCamelCase__				   =      get_linear_schedule_with_warmup(a__      , 0      , a__      )
       torch.cuda.empty_cache()
       return model, lm_optimizer, lm_scheduler







def   lowerCAmelCase(  a__    :  Optional[int]      , a__    :  Optional[int]      , a__    :  int      , a__    :  Optional[int]      ):







       '''simple docstring'''






       lowerCamelCase__				   =      np.array(a__      ).mean()
       lowerCamelCase__				   =      np.array(a__      ).std()
       lowerCamelCase__				   =      (real_perps - avg) / std
       lowerCamelCase__				   =      list(zip(a__      , a__      , a__      )      )
       joblib.dump(a__      , a__      )







def   lowerCAmelCase(  a__    :  Optional[int]      , a__    :  Any      , a__    :  List[str]      , a__    :  List[str]      , a__    :  List[str]      , a__    :  Tuple      , a__    :  List[str]      , a__    :  List[Any]="dev.jbl"      , a__    :  int=recopy_gpta      , ):







       '''simple docstring'''






       lowerCamelCase__				   =      []
       lowerCamelCase__				   =      []
       lowerCamelCase__				   =      []

       # Initialize the transformer model
       lowerCamelCase__				   =      copy.deepcopy(a__      )
       orig_model.to(device="cpu"      )
       torch.cuda.empty_cache()

       # Compute perplexity of initial transformer model for comparison
       model.train()
       lowerCamelCase__				   =      recopy_model(a__      , a__      , a__      )

       for step in tqdm(range(a__      )      ):
              lowerCamelCase__				   =      torch.zeros((1, context_len)      , dtype=torch.long      , device=a__      )
              lowerCamelCase__				   =      random.choice(a__      )
              lowerCamelCase__				   =      random.randint(0      , len(story[0]      ) - context_len - 1      )
              lowerCamelCase__				   =      story[0][start : start + context_len]
              lm_optimizer.zero_grad()
              lowerCamelCase__				   =      model(a__      , labels=a__      )
              lowerCamelCase__				   =      outputs[0]
              lowerCamelCase__				   =      compute_perplexity(a__      , a__      , a__      )
              model.train()
              lm_loss.backward()
              # Do LM backprop
              torch.nn.utils.clip_grad_norm_(model.parameters()      , 3.0      )
              lm_optimizer.step()
              lm_scheduler.step()  # Update learning rate schedule

              # Compute perplexity after back-propagating on the selected context
              lowerCamelCase__				   =      compute_perplexity(a__      , a__      , a__      )

              # Periodically save the stored (X, IG(X)) pairs
              if step % 1000 == 0 and step > 1:
                     intermittent_save(a__      , a__      , a__      , a__      )

              # Reset the pretrained model to the original pretrained GPT-2 weights after each iteration
              lowerCamelCase__				   =      recopy_model(a__      , a__      , a__      )

              past_perps.append(past_perp.item()      )
              real_perps.append(orig_perp - real_perp.item()      )
              contexts.append(np.array(context.cpu()      )      )

       intermittent_save(a__      , a__      , a__      , a__      )







def   lowerCAmelCase(  a__    :  Optional[int]      , a__    :  List[Any]="data/tokenized_stories_train_wikitext103.jbl"      , a__    :  List[Any]=100      , a__    :  Tuple=1026      , a__    :  Tuple=True      ):







       '''simple docstring'''






       lowerCamelCase__				   =      joblib.load(a__      )
       print("data loaded"      )
       lowerCamelCase__				   =      []
       if trim:
              for i, example in enumerate(a__      ):
                     if len(example[0]      ) > min_len:
                            lowerCamelCase__				   =      random.randint(0      , len(example[0]      ) - context_len - 1      )
                            objective_set.append(example[0, start : start + context_len]      )
                     if len(a__      ) >= number:
                            break
              lowerCamelCase__				   =      []
              for j in range(i + 1      , len(a__      )      ):
                     if len(data[j][0]      ) > min_len:
                            train_data.append(data[j]      )
       else:
              lowerCamelCase__				   =      data[0:number]
              lowerCamelCase__				   =      data[number:]

       joblib.dump(a__      , "objective_set.jbl"      )
       print("objective set saved"      )
       return train_data, objective_set







def   lowerCAmelCase(  a__    :  Optional[Any]      , a__    :  Dict      , a__    :  Tuple      , a__    :  Optional[int]      , a__    :  List[Any]=50      , a__    :  str="secondary_learner.pt"      ):







       '''simple docstring'''






       lowerCamelCase__				   =      torch.device("cuda:0" if torch.cuda.is_available() else "cpu"      )
       # We will use the first 512 pairs from our dataset as a test set for
       # our secondary learner and the rest to train
       lowerCamelCase__				   =      train_dataset[:512]
       lowerCamelCase__				   =      train_dataset[512:]
       lowerCamelCase__				   =      DataLoader(a__      , shuffle=a__      , batch_size=a__      )
       lowerCamelCase__				   =      DataLoader(a__      , shuffle=a__      , batch_size=a__      )

       # secondary learner model set up
       lowerCamelCase__				   =      nn.MSELoss()
       lowerCamelCase__				   =      nn.MSELoss(reduction="sum"      )
       secondary_learner.to(a__      )
       lowerCamelCase__				   =      torch.optim.Adam(secondary_learner.parameters()      , lr=0.0_0_0_0_1      )
       secondary_learner.train()

       # TODO in original code this is written as number of actual batches seen
       # not number of items seen but other places it is number of items instead.
       # improve consistency! changed this to epochs for clarity
       lowerCamelCase__				   =      float("inf"      )
       # Iterate through batches until we've used max_steps batches
       for epoch in range(int(a__      )      ):
              lowerCamelCase__				   =      0.0
              secondary_learner.train()
              for step, batch in enumerate(a__      ):
                     lowerCamelCase__				   =      batch[0].to(a__      )
                     lowerCamelCase__				   =      batch[1].to(a__      )
                     lowerCamelCase__				   =      secondary_learner(a__      )
                     q_optimizer.zero_grad()
                     lowerCamelCase__				   =      loss(a__      , real_q.float()      )
                     q_loss.backward()
                     q_optimizer.step()
                     tr_q_loss += q_loss.item()

                     # model trains fairly quickly so we won't wait for a full epoch
                     # eval is triggered at eval_freq and end of epochs
                     if (step % eval_freq == 0 and step > 0) or ((step + 1) == len(a__      )):
                            lowerCamelCase__				   =      tr_q_loss / (step + 1)

                            secondary_learner.eval()
                            lowerCamelCase__				   =      0.0
                            lowerCamelCase__				   =      0.0
                            lowerCamelCase__				   =      []
                            lowerCamelCase__				   =      []
                            # Compute performance of the secondary learner after this batch
                            for stepa, batcha in enumerate(a__      ):
                                   lowerCamelCase__				   =      batcha[0].to(a__      )
                                   lowerCamelCase__				   =      batcha[1].to(a__      )
                                   lowerCamelCase__				   =      secondary_learner(a__      )
                                   q_lossa += test_loss(a__      , a__      ).item()
                                   sum_qa += torch.sum(a__      ).item()
                                   for ei, i in enumerate(predicted_qa.cpu().detach().numpy()      ):
                                          predicted.append(i.item()      )
                                   for ei, i in enumerate(real_qa.cpu().detach().numpy()      ):
                                          actual.append(i.item()      )

                            q_lossa /= len(a__      )
                            print(
                                "Epoch: "      , a__      , "step: "      , a__      , "Avg. q:"      , sum_qa / len(a__      )      , "Train Loss: "      , a__      , "Test Loss: "      , a__      , )
                            if q_lossa < best_test_loss:
                                   joblib.dump((predicted, actual)      , "pred_vs_actual.jbl"      )
                                   torch.save(secondary_learner.state_dict()      , a__      )
                                   lowerCamelCase__				   =      q_lossa

                     secondary_learner.train()
       return secondary_learner







class 		snake_case_       (						nn.Module						):



   """simple docstring"""





   def __init__( self			,   UpperCamelCase):
          super(_lowerCamelCase			,   self).__init__()
          lowerCamelCase__				   =      model.transformer.wte
          lowerCamelCase__				   =      copy.deepcopy(model.transformer.wte.weight)
          lowerCamelCase__				   =      nn.Convad(self.embeddings.weight.size(1)			,   2_56			,   3			,   padding=1)
          lowerCamelCase__				   =      nn.Sequential(nn.Linear(2_56			,   32)			,   nn.Dropout(p=0.1)			,   nn.Linear(32			,   32)			,   nn.Linear(32			,   1))







   def     __UpperCAmelCase      ( self			,   UpperCamelCase):
          lowerCamelCase__				   =      torch.max(self.conv(self.embeddings(_lowerCamelCase).squeeze(1).transpose(1			,   2))			,   2)[0]
          lowerCamelCase__				   =      self.fc(_lowerCamelCase)
          return qs.squeeze(1)







   @classmethod
   def     __UpperCAmelCase      ( cls			,   UpperCamelCase			,   UpperCamelCase):
          lowerCamelCase__				   =      cls(_lowerCamelCase)  # this calls __init__
          lowerCamelCase__				   =      torch.load(_lowerCamelCase)
          secondary_learner.load_state_dict(_lowerCamelCase)
          lowerCamelCase__				   =      model.transformer.wte
          lowerCamelCase__				   =      copy.deepcopy(model.transformer.wte.weight)
          return secondary_learner



import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionModelEditingPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

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


enable_full_determinism()






@skip_mps
class     a_       (			a__				,    a__				,    a__				,    unittest.TestCase							):



       """simple docstring"""
       __SCREAMING_SNAKE_CASE       :					List[Any]						=  StableDiffusionModelEditingPipeline
       __SCREAMING_SNAKE_CASE       :					Optional[int]						=  TEXT_TO_IMAGE_PARAMS
       __SCREAMING_SNAKE_CASE       :					int						=  TEXT_TO_IMAGE_BATCH_PARAMS
       __SCREAMING_SNAKE_CASE       :					Any						=  TEXT_TO_IMAGE_IMAGE_PARAMS
       __SCREAMING_SNAKE_CASE       :					List[Any]						=  TEXT_TO_IMAGE_IMAGE_PARAMS






       def 	__lowerCAmelCase     (		self   )					->int:
           torch.manual_seed(0   )
           SCREAMING_SNAKE_CASE				:				Dict				      = 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				,       )
           SCREAMING_SNAKE_CASE				:				Dict				      = DDIMScheduler()
           torch.manual_seed(0   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = 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				,       )
           torch.manual_seed(0   )
           SCREAMING_SNAKE_CASE				:				List[str]				      = 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=1000				,       )
           SCREAMING_SNAKE_CASE				:				Dict				      = CLIPTextModel(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Tuple				      = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

           SCREAMING_SNAKE_CASE				:				List[Any]				      = {
               '''unet''': unet,
               '''scheduler''': scheduler,
               '''vae''': vae,
               '''text_encoder''': text_encoder,
               '''tokenizer''': tokenizer,
               '''safety_checker''': None,
               '''feature_extractor''': None,
           }
           return components






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase=0   )					->Optional[int]:
           SCREAMING_SNAKE_CASE				:				Any				      = torch.manual_seed(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = {
               '''prompt''': '''A field of roses''',
               '''generator''': generator,
               # Setting height and width to None to prevent OOMs on CPU.
               '''height''': None,
               '''width''': None,
               '''num_inference_steps''': 2,
               '''guidance_scale''': 6.0,
               '''output_type''': '''numpy''',
           }
           return inputs






       def 	__lowerCAmelCase     (		self   )					->Optional[int]:
           SCREAMING_SNAKE_CASE				:				Tuple				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				Any				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				List[Any]				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

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

           SCREAMING_SNAKE_CASE				:				List[str]				      = np.array([0.4_7_5_5, 0.5_1_3_2, 0.4_9_7_6, 0.3_9_0_4, 0.3_5_5_4, 0.4_7_6_5, 0.5_1_3_9, 0.5_1_5_8, 0.4_8_8_9]   )

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






       def 	__lowerCAmelCase     (		self   )					->List[Any]:
           SCREAMING_SNAKE_CASE				:				Dict				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				Tuple				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				str				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Any				      = self.get_dummy_inputs(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				List[str]				      = '''french fries'''
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = sd_pipe(**_lowerCamelCase				,       negative_prompt=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Any				      = output.images
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = image[0, -3:, -3:, -1]

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

           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = np.array([0.4_9_9_2, 0.5_1_0_1, 0.5_0_0_4, 0.3_9_4_9, 0.3_6_0_4, 0.4_7_3_5, 0.5_2_1_6, 0.5_2_0_4, 0.4_9_1_3]   )

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






       def 	__lowerCAmelCase     (		self   )					->Union[str, Any]:
           SCREAMING_SNAKE_CASE				:				List[str]				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				List[Any]				      = EulerAncestralDiscreteScheduler(
               beta_start=0.0_0_0_8_5				,       beta_end=0.0_1_2				,       beta_schedule='''scaled_linear'''   )
           SCREAMING_SNAKE_CASE				:				List[Any]				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = self.get_dummy_inputs(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = sd_pipe(**_lowerCamelCase   ).images
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = image[0, -3:, -3:, -1]

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

           SCREAMING_SNAKE_CASE				:				str				      = np.array([0.4_7_4_7, 0.5_3_7_2, 0.4_7_7_9, 0.4_9_8_2, 0.5_5_4_3, 0.4_8_1_6, 0.5_2_3_8, 0.4_9_0_4, 0.5_0_2_7]   )

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






       def 	__lowerCAmelCase     (		self   )					->Any:
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				List[Any]				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = PNDMScheduler()
           SCREAMING_SNAKE_CASE				:				Tuple				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = self.get_dummy_inputs(_lowerCamelCase   )
           # the pipeline does not expect pndm so test if it raises error.
           with self.assertRaises(_lowerCamelCase   ):
               SCREAMING_SNAKE_CASE				:				Dict				      = sd_pipe(**_lowerCamelCase   ).images






       def 	__lowerCAmelCase     (		self   )					->Dict:
           super().test_inference_batch_single_identical(expected_max_diff=5e-3   )






       def 	__lowerCAmelCase     (		self   )					->List[Any]:
           super().test_attention_slicing_forward_pass(expected_max_diff=5e-3   )






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



       """simple docstring"""






       def 	__lowerCAmelCase     (		self   )					->Dict:
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase=0   )					->Dict:
           SCREAMING_SNAKE_CASE				:				str				      = torch.manual_seed(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				List[Any]				      = {
               '''prompt''': '''A field of roses''',
               '''generator''': generator,
               '''num_inference_steps''': 3,
               '''guidance_scale''': 7.5,
               '''output_type''': '''numpy''',
           }
           return inputs






       def 	__lowerCAmelCase     (		self   )					->List[str]:
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = '''CompVis/stable-diffusion-v1-4'''
           SCREAMING_SNAKE_CASE				:				List[str]				      = StableDiffusionModelEditingPipeline.from_pretrained(_lowerCamelCase				,       safety_checker=_lowerCamelCase   )
           pipe.to(_lowerCamelCase   )
           pipe.set_progress_bar_config(disable=_lowerCamelCase   )
           pipe.enable_attention_slicing()

           SCREAMING_SNAKE_CASE				:				Any				      = self.get_inputs()
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = pipe(**_lowerCamelCase   ).images
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = image[0, -3:, -3:, -1].flatten()

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

           SCREAMING_SNAKE_CASE				:				str				      = np.array(
               [0.6_7_4_9_4_9_6, 0.6_3_8_6_4_5_3, 0.5_1_4_4_3_2_6_7, 0.6_6_0_9_4_9_0_5, 0.6_1_9_2_1_2_1_5, 0.5_4_9_1_3_3_2, 0.5_7_4_4_4_1_7, 0.5_8_0_7_5_1_0_6, 0.5_1_7_4_6_5_8]   )

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

           # make sure image changes after editing
           pipe.edit_model('''A pack of roses'''				,       '''A pack of blue roses'''   )

           SCREAMING_SNAKE_CASE				:				Any				      = pipe(**_lowerCamelCase   ).images
           SCREAMING_SNAKE_CASE				:				List[str]				      = image[0, -3:, -3:, -1].flatten()

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

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






       def 	__lowerCAmelCase     (		self   )					->str:
           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           SCREAMING_SNAKE_CASE				:				Optional[int]				      = '''CompVis/stable-diffusion-v1-4'''
           SCREAMING_SNAKE_CASE				:				Any				      = DDIMScheduler.from_pretrained(_lowerCamelCase				,       subfolder='''scheduler'''   )
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = StableDiffusionModelEditingPipeline.from_pretrained(
               _lowerCamelCase				,       scheduler=_lowerCamelCase				,       safety_checker=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Dict				      = pipe.to(_lowerCamelCase   )
           pipe.set_progress_bar_config(disable=_lowerCamelCase   )
           pipe.enable_attention_slicing(1   )
           pipe.enable_sequential_cpu_offload()

           SCREAMING_SNAKE_CASE				:				List[Any]				      = self.get_inputs()
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = pipe(**_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = torch.cuda.max_memory_allocated()
           # make sure that less than 4.4 GB is allocated
           assert mem_bytes < 4.4 * 10**9
