





'''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.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu






class    UpperCAmelCase	(       unittest.TestCase				):
 def      UpperCAmelCase_							(				self      :Any							)->							List[str]:
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()
 @property
 def      UpperCAmelCase_							(				self      :Tuple							)->							Union[str, Any]:
     A__				=			1
     A__				=			3
     A__				=			(32, 32)

     A__				=			floats_tensor((batch_size, num_channels) + sizes						,       rng=random.Random(0							)							).to(lowercase_							)
     return image
 @property
 def      UpperCAmelCase_							(				self      :Any							)->							List[str]:
     torch.manual_seed(0							)
     A__				=			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						,       )
     return model
 @property
 def      UpperCAmelCase_							(				self      :int							)->							List[Any]:
     torch.manual_seed(0							)
     A__				=			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						,       )
     return model
 @property
 def      UpperCAmelCase_							(				self      :int							)->							List[str]:
     torch.manual_seed(0							)
     A__				=			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						,       )
     return CLIPTextModel(lowercase_							)
 @property
 def      UpperCAmelCase_							(				self      :Dict							)->							List[Any]:




     def extract(*lowercase_      :List[str]						,       **lowercase_      :Dict							):






         class    UpperCAmelCase	:
          def __init__(				self      :int							)->							Any:
              A__				=			torch.ones([0]							)



          def      UpperCAmelCase_							(				self      :List[str]						,       lowercase_      :Tuple							)->							Any:
              self.pixel_values.to(lowercase_							)
              return self

         return Out()

     return extract
 def      UpperCAmelCase_							(				self      :Optional[int]							)->							str:
     A__				=			'cpu'  # ensure determinism for the device-dependent torch.Generator
     A__				=			self.dummy_cond_unet
     A__				=			DDIMScheduler(
         beta_start=0.0_0_0_8_5						,       beta_end=0.0_1_2						,       beta_schedule="scaled_linear"						,       clip_sample=lowercase_						,       set_alpha_to_one=lowercase_						,       )

     A__				=			self.dummy_vae
     A__				=			self.dummy_text_encoder
     A__				=			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							)

     # make sure here that pndm scheduler skips prk
     A__				=			StableDiffusionPipeline(
         unet=lowercase_						,       scheduler=lowercase_						,       vae=lowercase_						,       text_encoder=lowercase_						,       tokenizer=lowercase_						,       safety_checker=lowercase_						,       feature_extractor=self.dummy_extractor						,       )
     A__				=			sd_pipe.to(lowercase_							)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__				=			'A painting of a squirrel eating a burger'

     A__				=			torch.Generator(device=lowercase_							).manual_seed(0							)
     A__				=			sd_pipe([prompt]						,       generator=lowercase_						,       guidance_scale=6.0						,       num_inference_steps=2						,       output_type="np"							)
     A__				=			output.images

     A__				=			torch.Generator(device=lowercase_							).manual_seed(0							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=6.0						,       num_inference_steps=2						,       output_type="np"						,       return_dict=lowercase_						,       )[0]

     A__				=			image[0, -3:, -3:, -1]
     A__				=			image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     A__				=			np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4]							)

     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      UpperCAmelCase_							(				self      :Tuple							)->							Dict:
     A__				=			'cpu'  # ensure determinism for the device-dependent torch.Generator
     A__				=			self.dummy_cond_unet
     A__				=			PNDMScheduler(skip_prk_steps=lowercase_							)
     A__				=			self.dummy_vae
     A__				=			self.dummy_text_encoder
     A__				=			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							)

     # make sure here that pndm scheduler skips prk
     A__				=			StableDiffusionPipeline(
         unet=lowercase_						,       scheduler=lowercase_						,       vae=lowercase_						,       text_encoder=lowercase_						,       tokenizer=lowercase_						,       safety_checker=lowercase_						,       feature_extractor=self.dummy_extractor						,       )
     A__				=			sd_pipe.to(lowercase_							)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__				=			'A painting of a squirrel eating a burger'
     A__				=			torch.Generator(device=lowercase_							).manual_seed(0							)
     A__				=			sd_pipe([prompt]						,       generator=lowercase_						,       guidance_scale=6.0						,       num_inference_steps=2						,       output_type="np"							)

     A__				=			output.images

     A__				=			torch.Generator(device=lowercase_							).manual_seed(0							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=6.0						,       num_inference_steps=2						,       output_type="np"						,       return_dict=lowercase_						,       )[0]

     A__				=			image[0, -3:, -3:, -1]
     A__				=			image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     A__				=			np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3]							)

     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      UpperCAmelCase_							(				self      :Tuple							)->							Dict:
     A__				=			StableDiffusionPipeline.from_pretrained(
         "hf-internal-testing/tiny-stable-diffusion-lms-pipe"						,       safety_checker=lowercase_							)
     assert isinstance(lowercase_						,       lowercase_							)
     assert isinstance(pipe.scheduler						,       lowercase_							)
     assert pipe.safety_checker is None

     A__				=			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(lowercase_							)
         A__				=			StableDiffusionPipeline.from_pretrained(lowercase_							)

     # sanity check that the pipeline still works
     assert pipe.safety_checker is None
     A__				=			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      UpperCAmelCase_							(				self      :Union[str, Any]							)->							Dict:
     A__				=			self.dummy_cond_unet
     A__				=			PNDMScheduler(skip_prk_steps=lowercase_							)
     A__				=			self.dummy_vae
     A__				=			self.dummy_text_encoder
     A__				=			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							)

     # put models in fp16
     A__				=			unet.half()
     A__				=			vae.half()
     A__				=			bert.half()

     # make sure here that pndm scheduler skips prk
     A__				=			StableDiffusionPipeline(
         unet=lowercase_						,       scheduler=lowercase_						,       vae=lowercase_						,       text_encoder=lowercase_						,       tokenizer=lowercase_						,       safety_checker=lowercase_						,       feature_extractor=self.dummy_extractor						,       )
     A__				=			sd_pipe.to(lowercase_							)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__				=			'A painting of a squirrel eating a burger'
     A__				=			sd_pipe([prompt]						,       num_inference_steps=2						,       output_type="np"							).images

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






@nightly
@require_torch_gpu
class    UpperCAmelCase	(       unittest.TestCase				):
 def      UpperCAmelCase_							(				self      :List[Any]							)->							Tuple:
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()
 def      UpperCAmelCase_							(				self      :int							)->							Dict:
     A__				=			StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"						,       safety_checker=lowercase_							)
     A__				=			LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config							)
     A__				=			sd_pipe.to(lowercase_							)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__				=			(
         'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'
         ' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'
         ' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'
         ' children from bahnhof zoo, detailed '
     )
     A__				=			40_03_66_03_46
     A__				=			7

     # without safety guidance (sld_guidance_scale = 0)
     A__				=			torch.manual_seed(lowercase_							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=lowercase_						,       num_inference_steps=50						,       output_type="np"						,       width=5_12						,       height=5_12						,       sld_guidance_scale=0						,       )

     A__				=			output.images
     A__				=			image[0, -3:, -3:, -1]
     A__				=			[0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6]

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

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

     # without safety guidance (strong configuration)
     A__				=			torch.manual_seed(lowercase_							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=lowercase_						,       num_inference_steps=50						,       output_type="np"						,       width=5_12						,       height=5_12						,       sld_guidance_scale=20_00						,       sld_warmup_steps=7						,       sld_threshold=0.0_2_5						,       sld_momentum_scale=0.5						,       sld_mom_beta=0.7						,       )

     A__				=			output.images
     A__				=			image[0, -3:, -3:, -1]
     A__				=			[0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9]

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

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 def      UpperCAmelCase_							(				self      :Any							)->							Union[str, Any]:
     A__				=			StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"						,       safety_checker=lowercase_							)
     A__				=			LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config							)
     A__				=			sd_pipe.to(lowercase_							)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__				=			'padme amidala taking a bath artwork, safe for work, no nudity'
     A__				=			27_34_97_17_55
     A__				=			7

     A__				=			torch.manual_seed(lowercase_							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=lowercase_						,       num_inference_steps=50						,       output_type="np"						,       width=5_12						,       height=5_12						,       sld_guidance_scale=0						,       )

     A__				=			output.images
     A__				=			image[0, -3:, -3:, -1]
     A__				=			[0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7]

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

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

     A__				=			torch.manual_seed(lowercase_							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=lowercase_						,       num_inference_steps=50						,       output_type="np"						,       width=5_12						,       height=5_12						,       sld_guidance_scale=20_00						,       sld_warmup_steps=7						,       sld_threshold=0.0_2_5						,       sld_momentum_scale=0.5						,       sld_mom_beta=0.7						,       )

     A__				=			output.images
     A__				=			image[0, -3:, -3:, -1]
     A__				=			[0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3]

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

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



 def      UpperCAmelCase_							(				self      :List[Any]							)->							int:
     A__				=			StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"							)
     A__				=			sd_pipe.to(lowercase_							)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__				=			(
         'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'
         ' leyendecker'
     )
     A__				=			10_44_35_52_34
     A__				=			12

     A__				=			torch.manual_seed(lowercase_							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=lowercase_						,       num_inference_steps=50						,       output_type="np"						,       width=5_12						,       height=5_12						,       sld_guidance_scale=0						,       )

     A__				=			output.images
     A__				=			image[0, -3:, -3:, -1]
     A__				=			np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]							)

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

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

     A__				=			torch.manual_seed(lowercase_							)
     A__				=			sd_pipe(
         [prompt]						,       generator=lowercase_						,       guidance_scale=lowercase_						,       num_inference_steps=50						,       output_type="np"						,       width=5_12						,       height=5_12						,       sld_guidance_scale=20_00						,       sld_warmup_steps=7						,       sld_threshold=0.0_2_5						,       sld_momentum_scale=0.5						,       sld_mom_beta=0.7						,       )

     A__				=			output.images
     A__				=			image[0, -3:, -3:, -1]
     A__				=			np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1]							)
     assert image.shape == (1, 5_12, 5_12, 3)

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







from collections.abc import Generator
from math import sin




def 	a_      (    SCREAMING_SNAKE_CASE__					:      bytes     ):
       '''simple docstring'''





       if len(SCREAMING_SNAKE_CASE__     ) != 32:
              raise ValueError('Input must be of length 32'     )

       _lowerCamelCase       :		Any		=b''
       for i in [3, 2, 1, 0]:
              little_endian += string_aa[8 * i : 8 * i + 8]
       return little_endian




def 	a_      (    SCREAMING_SNAKE_CASE__					:      int     ):
       '''simple docstring'''





       if i < 0:
              raise ValueError('Input must be non-negative'     )

       _lowerCamelCase       :		Optional[int]		=format(SCREAMING_SNAKE_CASE__		,			'08x'     )[-8:]
       _lowerCamelCase       :		List[Any]		=b''
       for i in [3, 2, 1, 0]:
              little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('utf-8'     )
       return little_endian_hex




def 	a_      (    SCREAMING_SNAKE_CASE__					:      bytes     ):
       '''simple docstring'''





       _lowerCamelCase       :		Dict		=b''
       for char in message:
              bit_string += format(SCREAMING_SNAKE_CASE__		,			'08b'     ).encode('utf-8'     )
       _lowerCamelCase       :		Dict		=format(len(SCREAMING_SNAKE_CASE__     )		,			'064b'     ).encode('utf-8'     )

       # Pad bit_string to a multiple of 512 chars
       bit_string += b"1"
       while len(SCREAMING_SNAKE_CASE__     ) % 512 != 448:
              bit_string += b"0"
       bit_string += to_little_endian(start_len[32:]     ) + to_little_endian(start_len[:32]     )

       return bit_string




def 	a_      (    SCREAMING_SNAKE_CASE__					:      bytes     ):
       '''simple docstring'''





       if len(SCREAMING_SNAKE_CASE__     ) % 512 != 0:
              raise ValueError('Input must have length that\'s a multiple of 512'     )

       for pos in range(0		,			len(SCREAMING_SNAKE_CASE__     )		,			512     ):
              _lowerCamelCase       :		str		=bit_string[pos : pos + 512]
              _lowerCamelCase       :		Tuple		=[]
              for i in range(0		,			512		,			32     ):
                     block_words.append(int(to_little_endian(block[i : i + 32]     )		,			2     )     )
              yield block_words




def 	a_      (    SCREAMING_SNAKE_CASE__					:      int     ):
       '''simple docstring'''





       if i < 0:
              raise ValueError('Input must be non-negative'     )

       _lowerCamelCase       :		List[str]		=format(SCREAMING_SNAKE_CASE__		,			'032b'     )
       _lowerCamelCase       :		List[str]		=''
       for c in i_str:
              new_str += "1" if c == "0" else "0"
       return int(SCREAMING_SNAKE_CASE__		,			2     )




def 	a_      (    SCREAMING_SNAKE_CASE__					:      int		,			SCREAMING_SNAKE_CASE__					:      int     ):
       '''simple docstring'''





       return (a + b) % 2**32




def 	a_      (    SCREAMING_SNAKE_CASE__					:      int		,			SCREAMING_SNAKE_CASE__					:      int     ):
       '''simple docstring'''





       if i < 0:
              raise ValueError('Input must be non-negative'     )
       if shift < 0:
              raise ValueError('Shift must be non-negative'     )
       return ((i << shift) ^ (i >> (32 - shift))) % 2**32




def 	a_      (    SCREAMING_SNAKE_CASE__					:      bytes     ):
       '''simple docstring'''





       _lowerCamelCase       :		int		=preprocess(SCREAMING_SNAKE_CASE__     )

       _lowerCamelCase       :		Dict		=[int(2**32 * abs(sin(i + 1     )     )     ) for i in range(64     )]

       # Starting states
       _lowerCamelCase       :		str		=0X67_45_23_01
       _lowerCamelCase       :		Union[str, Any]		=0Xef_cd_ab_89
       _lowerCamelCase       :		List[str]		=0X98_ba_dc_fe
       _lowerCamelCase       :		int		=0X10_32_54_76

       _lowerCamelCase       :		Optional[int]		=[
           7,
           12,
           17,
           22,
           7,
           12,
           17,
           22,
           7,
           12,
           17,
           22,
           7,
           12,
           17,
           22,
           5,
           9,
           14,
           20,
           5,
           9,
           14,
           20,
           5,
           9,
           14,
           20,
           5,
           9,
           14,
           20,
           4,
           11,
           16,
           23,
           4,
           11,
           16,
           23,
           4,
           11,
           16,
           23,
           4,
           11,
           16,
           23,
           6,
           10,
           15,
           21,
           6,
           10,
           15,
           21,
           6,
           10,
           15,
           21,
           6,
           10,
           15,
           21,
       ]

       # Process bit string in chunks, each with 16 32-char words
       for block_words in get_block_words(SCREAMING_SNAKE_CASE__     ):
              _lowerCamelCase       :		Union[str, Any]		=aa
              _lowerCamelCase       :		List[Any]		=ba
              _lowerCamelCase       :		Dict		=ca
              _lowerCamelCase       :		List[Any]		=da

              # Hash current chunk
              for i in range(64     ):
                     if i <= 15:
                            # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
                            _lowerCamelCase       :		Optional[Any]		=d ^ (b & (c ^ d))
                            _lowerCamelCase       :		Dict		=i
                     elif i <= 31:
                            # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
                            _lowerCamelCase       :		Optional[int]		=c ^ (d & (b ^ c))
                            _lowerCamelCase       :		List[str]		=(5 * i + 1) % 16
                     elif i <= 47:
                            _lowerCamelCase       :		str		=b ^ c ^ d
                            _lowerCamelCase       :		int		=(3 * i + 5) % 16
                     else:
                            _lowerCamelCase       :		Optional[Any]		=c ^ (b | not_aa(SCREAMING_SNAKE_CASE__     ))
                            _lowerCamelCase       :		Dict		=(7 * i) % 16
                     _lowerCamelCase       :		Any		=(f + a + added_consts[i] + block_words[g]) % 2**32
                     _lowerCamelCase       :		str		=d
                     _lowerCamelCase       :		Any		=c
                     _lowerCamelCase       :		Union[str, Any]		=b
                     _lowerCamelCase       :		Dict		=sum_aa(SCREAMING_SNAKE_CASE__		,			left_rotate_aa(SCREAMING_SNAKE_CASE__		,			shift_amounts[i]     )     )

              # Add hashed chunk to running total
              _lowerCamelCase       :		Optional[Any]		=sum_aa(SCREAMING_SNAKE_CASE__		,			SCREAMING_SNAKE_CASE__     )
              _lowerCamelCase       :		List[str]		=sum_aa(SCREAMING_SNAKE_CASE__		,			SCREAMING_SNAKE_CASE__     )
              _lowerCamelCase       :		Optional[int]		=sum_aa(SCREAMING_SNAKE_CASE__		,			SCREAMING_SNAKE_CASE__     )
              _lowerCamelCase       :		List[str]		=sum_aa(SCREAMING_SNAKE_CASE__		,			SCREAMING_SNAKE_CASE__     )

       _lowerCamelCase       :		List[Any]		=reformat_hex(SCREAMING_SNAKE_CASE__     ) + reformat_hex(SCREAMING_SNAKE_CASE__     ) + reformat_hex(SCREAMING_SNAKE_CASE__     ) + reformat_hex(SCREAMING_SNAKE_CASE__     )
       return digest


if __name__ == "__main__":
 import doctest

 doctest.testmod()


