




"""simple docstring"""





import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()

class  __lowercase    (     snake_case_  ,				snake_case_  ,				unittest.TestCase		):


				'''simple docstring'''


				_lowerCAmelCase		     =StableDiffusionXLPipeline
				_lowerCAmelCase		     =TEXT_TO_IMAGE_PARAMS
				_lowerCAmelCase		     =TEXT_TO_IMAGE_BATCH_PARAMS
				_lowerCAmelCase		     =TEXT_TO_IMAGE_IMAGE_PARAMS
				_lowerCAmelCase		     =TEXT_TO_IMAGE_IMAGE_PARAMS

				def  _lowerCamelCase   (				self				:       Tuple ):
										torch.manual_seed(0 )
										snake_case__    :   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''') ,attention_head_dim=(2, 4) ,use_linear_projection=SCREAMING_SNAKE_CASE_ ,addition_embed_type='''text_time''' ,addition_time_embed_dim=8 ,transformer_layers_per_block=(1, 2) ,projection_class_embeddings_input_dim=8_0 ,cross_attention_dim=6_4 ,)
										snake_case__    :   List[str]							     =   EulerDiscreteScheduler(
										    beta_start=0.00085 ,beta_end=0.012 ,steps_offset=1 ,beta_schedule='''scaled_linear''' ,timestep_spacing='''leading''' ,)
										torch.manual_seed(0 )
										snake_case__    :   Optional[Any]							     =   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 ,sample_size=1_2_8 ,)
										torch.manual_seed(0 )
										snake_case__    :   List[Any]							     =   CLIPTextConfig(
										    bos_token_id=0 ,eos_token_id=2 ,hidden_size=3_2 ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,hidden_act='''gelu''' ,projection_dim=3_2 ,)
										snake_case__    :   Optional[int]							     =   CLIPTextModel(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   List[str]							     =   CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,local_files_only=SCREAMING_SNAKE_CASE_ )

										snake_case__    :   int							     =   CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Optional[Any]							     =   CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,local_files_only=SCREAMING_SNAKE_CASE_ )

										snake_case__    :   List[Any]							     =   {
										    '''unet''': unet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''text_encoder_2''': text_encoder_a,
										    '''tokenizer_2''': tokenizer_a,
										    # "safety_checker": None,
										    # "feature_extractor": None,
										}
										return components

				def  _lowerCamelCase   (				self				:       Tuple ,SCREAMING_SNAKE_CASE_				:       Optional[Any] ,SCREAMING_SNAKE_CASE_				:       Optional[int]=0 ):
										if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ):
																snake_case__    :   List[Any]							     =   torch.manual_seed(SCREAMING_SNAKE_CASE_ )
										else:
																snake_case__    :   Any							     =   torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Dict							     =   {
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 5.0,
										    '''output_type''': '''numpy''',
										}
										return inputs

				def  _lowerCamelCase   (				self				:       Union[str, Any] ):
										snake_case__    :   List[Any]							     =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
										snake_case__    :   Any							     =   self.get_dummy_components()
										snake_case__    :   Optional[Any]							     =   StableDiffusionXLPipeline(**SCREAMING_SNAKE_CASE_ )
										snake_case__    :   List[str]							     =   sd_pipe.to(SCREAMING_SNAKE_CASE_ )
										sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )

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

										assert image.shape == (1, 6_4, 6_4, 3)
										snake_case__    :   List[str]							     =   np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747] )

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

				def  _lowerCamelCase   (				self				:       Dict ):
										snake_case__    :   List[str]							     =   self.get_dummy_components()
										snake_case__    :   Any							     =   StableDiffusionXLPipeline(**SCREAMING_SNAKE_CASE_ )
										snake_case__    :   List[str]							     =   sd_pipe.to(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   List[str]							     =   sd_pipe.to(SCREAMING_SNAKE_CASE_ )
										sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )

										# forward without prompt embeds
										snake_case__    :   Union[str, Any]							     =   self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   List[str]							     =   3 * ['''this is a negative prompt''']
										snake_case__    :   str							     =   negative_prompt
										snake_case__    :   Dict							     =   3 * [inputs['''prompt''']]

										snake_case__    :   Any							     =   sd_pipe(**SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Optional[Any]							     =   output.images[0, -3:, -3:, -1]

										# forward with prompt embeds
										snake_case__    :   Optional[Any]							     =   self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   int							     =   3 * ['''this is a negative prompt''']
										snake_case__    :   Tuple							     =   3 * [inputs.pop('''prompt''' )]

										(
										    (
										    snake_case__
										)     ,		(
										    snake_case__
										)     ,		(
										    snake_case__
										)     ,		(
										    snake_case__
										)     ,		
										)    :   Tuple							     =   sd_pipe.encode_prompt(SCREAMING_SNAKE_CASE_ ,negative_prompt=SCREAMING_SNAKE_CASE_ )

										snake_case__    :   Optional[Any]							     =   sd_pipe(
										    **SCREAMING_SNAKE_CASE_ ,prompt_embeds=SCREAMING_SNAKE_CASE_ ,negative_prompt_embeds=SCREAMING_SNAKE_CASE_ ,pooled_prompt_embeds=SCREAMING_SNAKE_CASE_ ,negative_pooled_prompt_embeds=SCREAMING_SNAKE_CASE_ ,)
										snake_case__    :   int							     =   output.images[0, -3:, -3:, -1]

										# make sure that it's equal
										assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4

				def  _lowerCamelCase   (				self				:       Optional[Any] ):
										super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 )





				def  _lowerCamelCase   (				self				:       Any ):
										super().test_inference_batch_single_identical(expected_max_diff=3E-3 )







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


				'''simple docstring'''


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

				def  _lowerCamelCase   (				self				:       Optional[Any] ,SCREAMING_SNAKE_CASE_				:       Optional[int] ,SCREAMING_SNAKE_CASE_				:       Tuple="cpu" ,SCREAMING_SNAKE_CASE_				:       int=torch.floataa ,SCREAMING_SNAKE_CASE_				:       Tuple=0 ):
										snake_case__    :   Tuple							     =   torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   str							     =   np.random.RandomState(SCREAMING_SNAKE_CASE_ ).standard_normal((1, 4, 6_4, 6_4) )
										snake_case__    :   Tuple							     =   torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ ,dtype=SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Optional[int]							     =   {
										    '''prompt''': '''a photograph of an astronaut riding a horse''',
										    '''latents''': latents,
										    '''generator''': generator,
										    '''num_inference_steps''': 3,
										    '''guidance_scale''': 7.5,
										    '''output_type''': '''numpy''',
										}
										return inputs





				def  _lowerCamelCase   (				self				:       Tuple ):
										snake_case__    :   Any							     =   DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' )
										pipe.to(SCREAMING_SNAKE_CASE_ )
										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )

										snake_case__    :   Union[str, Any]							     =   self.get_inputs(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Dict							     =   pipe(**SCREAMING_SNAKE_CASE_ ).images
										snake_case__    :   int							     =   image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_1_2, 5_1_2, 3)
										snake_case__    :   Tuple							     =   np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506] )
										assert np.abs(image_slice - expected_slice ).max() < 7E-3








"""simple docstring"""





from __future__ import annotations

import math
import random

def 						lowerCAmelCase							(	lowerCamelCase ,     lowerCamelCase ,     lowerCamelCase						):
						'''simple docstring'''


						snake_case__    :   Tuple							     =   d * e - 1
						snake_case__    :   Optional[int]							     =   0
						snake_case__    :   Tuple							     =   0
						while p == 0:
												snake_case__    :   Optional[int]							     =   random.randint(2 ,     n - 1						)
												snake_case__    :   Tuple							     =   k
												while True:
																		if t % 2 == 0:
																								snake_case__    :   List[Any]							     =   t // 2
																								snake_case__    :   Union[str, Any]							     =   (g**t) % n
																								snake_case__    :   Dict							     =   math.gcd(x - 1 ,     lowerCamelCase						)
																								if x > 1 and y > 1:
																														snake_case__    :   Union[str, Any]							     =   y
																														snake_case__    :   str							     =   n // y
																														break  # find the correct factors
																		else:
																								break  # t is not divisible by 2, break and choose another g
						return sorted([p, q]						)


if __name__ == "__main__":
							import doctest

							doctest.testmod()


