



"""simple docstring"""







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   UpperCamelCase	(     SCREAMING_SNAKE_CASE__					,   SCREAMING_SNAKE_CASE__					,   SCREAMING_SNAKE_CASE__					,   unittest.TestCase       ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_							:       Union[str, Any]						       =  StableDiffusionModelEditingPipeline
	SCREAMING_SNAKE_CASE_							:       Optional[Any]						       =  TEXT_TO_IMAGE_PARAMS
	SCREAMING_SNAKE_CASE_							:       Union[str, Any]						       =  TEXT_TO_IMAGE_BATCH_PARAMS
	SCREAMING_SNAKE_CASE_							:       List[str]						       =  TEXT_TO_IMAGE_IMAGE_PARAMS
	SCREAMING_SNAKE_CASE_							:       List[Any]						       =  TEXT_TO_IMAGE_IMAGE_PARAMS






	def    lowerCamelCase__					(     self   ):
			torch.manual_seed(0   )
			_lowercase				: str     =   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				,)
			_lowercase				: Union[str, Any]     =   DDIMScheduler()
			torch.manual_seed(0   )
			_lowercase				: int     =   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   )
			_lowercase				: Optional[int]     =   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=10_00				,)
			_lowercase				: List[str]     =   CLIPTextModel(lowerCAmelCase_   )
			_lowercase				: List[Any]     =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

			_lowercase				: Optional[int]     =   {
			    '''unet''': unet,
			    '''scheduler''': scheduler,
			    '''vae''': vae,
			    '''text_encoder''': text_encoder,
			    '''tokenizer''': tokenizer,
			    '''safety_checker''': None,
			    '''feature_extractor''': None,
			}
			return components






	def    lowerCamelCase__					(     self				,UpperCAmelCase_				,UpperCAmelCase_=0   ):
			_lowercase				: Optional[int]     =   torch.manual_seed(lowerCAmelCase_   )
			_lowercase				: 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   ):
			_lowercase				: Tuple     =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			_lowercase				: int     =   self.get_dummy_components()
			_lowercase				: Any     =   StableDiffusionModelEditingPipeline(**lowerCAmelCase_   )
			_lowercase				: int     =   sd_pipe.to(lowerCAmelCase_   )
			sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_   )

			_lowercase				: Optional[Any]     =   self.get_dummy_inputs(lowerCAmelCase_   )
			_lowercase				: Optional[Any]     =   sd_pipe(**lowerCAmelCase_   ).images
			_lowercase				: List[Any]     =   image[0, -3:, -3:, -1]
			assert image.shape == (1, 64, 64, 3)

			_lowercase				: int     =   np.array([0.4755, 0.5132, 0.4976, 0.3904, 0.3554, 0.4765, 0.5139, 0.5158, 0.4889]   )

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






	def    lowerCamelCase__					(     self   ):
			_lowercase				: int     =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			_lowercase				: int     =   self.get_dummy_components()
			_lowercase				: Dict     =   StableDiffusionModelEditingPipeline(**lowerCAmelCase_   )
			_lowercase				: List[Any]     =   sd_pipe.to(lowerCAmelCase_   )
			sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_   )

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

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

			_lowercase				: Dict     =   np.array([0.4992, 0.5101, 0.5004, 0.3949, 0.3604, 0.4735, 0.5216, 0.5204, 0.4913]   )

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






	def    lowerCamelCase__					(     self   ):
			_lowercase				: int     =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			_lowercase				: Tuple     =   self.get_dummy_components()
			_lowercase				: Dict     =   EulerAncestralDiscreteScheduler(
			    beta_start=0.00085				,beta_end=0.012				,beta_schedule="""scaled_linear"""   )
			_lowercase				: Tuple     =   StableDiffusionModelEditingPipeline(**lowerCAmelCase_   )
			_lowercase				: Optional[int]     =   sd_pipe.to(lowerCAmelCase_   )
			sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_   )

			_lowercase				: Any     =   self.get_dummy_inputs(lowerCAmelCase_   )
			_lowercase				: Tuple     =   sd_pipe(**lowerCAmelCase_   ).images
			_lowercase				: Union[str, Any]     =   image[0, -3:, -3:, -1]

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

			_lowercase				: List[Any]     =   np.array([0.4747, 0.5372, 0.4779, 0.4982, 0.5543, 0.4816, 0.5238, 0.4904, 0.5027]   )

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






	def    lowerCamelCase__					(     self   ):
			_lowercase				: Optional[int]     =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
			_lowercase				: Optional[int]     =   self.get_dummy_components()
			_lowercase				: List[Any]     =   PNDMScheduler()
			_lowercase				: Any     =   StableDiffusionModelEditingPipeline(**lowerCAmelCase_   )
			_lowercase				: str     =   sd_pipe.to(lowerCAmelCase_   )
			sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_   )

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






	def    lowerCamelCase__					(     self   ):
			super().test_inference_batch_single_identical(expected_max_diff=5E-3   )






	def    lowerCamelCase__					(     self   ):
			super().test_attention_slicing_forward_pass(expected_max_diff=5E-3   )







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




	"""simple docstring"""






	def    lowerCamelCase__					(     self   ):
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()






	def    lowerCamelCase__					(     self				,UpperCAmelCase_=0   ):
			_lowercase				: Optional[Any]     =   torch.manual_seed(lowerCAmelCase_   )
			_lowercase				: Tuple     =   {
			    '''prompt''': '''A field of roses''',
			    '''generator''': generator,
			    '''num_inference_steps''': 3,
			    '''guidance_scale''': 7.5,
			    '''output_type''': '''numpy''',
			}
			return inputs






	def    lowerCamelCase__					(     self   ):
			_lowercase				: int     =   '''CompVis/stable-diffusion-v1-4'''
			_lowercase				: Optional[int]     =   StableDiffusionModelEditingPipeline.from_pretrained(lowerCAmelCase_				,safety_checker=lowerCAmelCase_   )
			pipe.to(lowerCAmelCase_   )
			pipe.set_progress_bar_config(disable=lowerCAmelCase_   )
			pipe.enable_attention_slicing()

			_lowercase				: Optional[int]     =   self.get_inputs()
			_lowercase				: Dict     =   pipe(**lowerCAmelCase_   ).images
			_lowercase				: Tuple     =   image[0, -3:, -3:, -1].flatten()

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

			_lowercase				: Optional[int]     =   np.array(
			    [0.6749496, 0.6386453, 0.51443267, 0.66094905, 0.61921215, 0.5491332, 0.5744417, 0.58075106, 0.5174658]   )

			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"""   )

			_lowercase				: Dict     =   pipe(**lowerCAmelCase_   ).images
			_lowercase				: Union[str, Any]     =   image[0, -3:, -3:, -1].flatten()

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

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






	def    lowerCamelCase__					(     self   ):
			torch.cuda.empty_cache()
			torch.cuda.reset_max_memory_allocated()
			torch.cuda.reset_peak_memory_stats()

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

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

			_lowercase				: Dict     =   torch.cuda.max_memory_allocated()
			# make sure that less than 4.4 GB is allocated
			assert mem_bytes < 4.4 * 10**9





import math as m






def     lowerCamelCase__				(   a						,						a						,						a=0.001 ) ->  Optional[int]:
   return (f(a + h ) - f(a - h )) / (2 * h)






def     lowerCamelCase__				(   a						,						a=0						,						a=1_00						,						a=0.0001						,						a=1E-6						,						a=False ) ->  List[Any]:
   _A:    Optional[Any]						     =			xa  # set the initial guess
   _A:    Dict						     =			[a]
   _A:    Tuple						     =			abs(f(a ) )
   _A:    Tuple						     =			lambda a : calc_derivative(a						,						a						,						h=a )  # noqa: E731  Derivative of f(x)
   for _ in range(a ):
      if fa(a ) == 0:
         raise ValueError('''No converging solution found''' )
      _A:    Any						     =			a - f(a ) / fa(a )  # Calculate the next estimate
      if logsteps:
         steps.append(a )
      if error < maxerror:
         break
   else:
      raise ValueError('''Iteration limit reached, no converging solution found''' )
   if logsteps:
      # If logstep is true, then log intermediate steps
      return a, error, steps
   return a, error


if __name__ == "__main__":
   from matplotlib import pyplot as plt

   UpperCAmelCase__						:	Optional[Any]	     = lambda x: m.tanh(x) ** 2 - m.exp(3 * x)  # noqa: E731
   UpperCAmelCase__     ,UpperCAmelCase__     ,UpperCAmelCase__						:	str	     = newton_raphson(
       f, xa=10, maxiter=1000, step=1E-6, logsteps=True
   )
   plt.plot([abs(f(x)) for x in steps])
   plt.xlabel('step')
   plt.ylabel('error')
   plt.show()
   print(F"""solution = {{{solution:f}}}, error = {{{error:f}}}""")



