






"""simple docstring"""

import gc
import random
import unittest

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

import diffusers
from diffusers import (
    AutoencoderKL,
    EulerDiscreteScheduler,
    StableDiffusionLatentUpscalePipeline,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
def _lowerCAmelCase	(  __lowerCamelCase:Optional[Any]   ):

						'''simple docstring'''






						__magic_name__            =     [tensor.shape for tensor in tensor_list]
						return all(shape == shapes[0] for shape in shapes[1:]   )

class 						A_							(      snake_case_					,							snake_case_					,							snake_case_					,							unittest.TestCase  ):
				UpperCAmelCase__        =				StableDiffusionLatentUpscalePipeline
				UpperCAmelCase__        =				TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
				    '''height''',
				    '''width''',
				    '''cross_attention_kwargs''',
				    '''negative_prompt_embeds''',
				    '''prompt_embeds''',
				}
				UpperCAmelCase__        =				PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''}
				UpperCAmelCase__        =				TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
				UpperCAmelCase__        =				frozenset(
				    []  )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
				UpperCAmelCase__        =				frozenset([]  )

				UpperCAmelCase__        =				True







				@property
				def     _snake_case					(							self							:						List[str]	)				->					Dict:
										__magic_name__            =     1
										__magic_name__            =     4
										__magic_name__            =     (1_6, 1_6)

										__magic_name__            =     floats_tensor((batch_size, num_channels) + sizes						,    rng=random.Random(0	)	).to(__lowerCamelCase	)
										return image







				def     _snake_case					(							self							:						str	)				->					Tuple:
										torch.manual_seed(0	)
										__magic_name__            =     UNetaDConditionModel(
										    act_fn="gelu"						,    attention_head_dim=8						,    norm_num_groups=__lowerCamelCase						,    block_out_channels=[3_2, 3_2, 6_4, 6_4]						,    time_cond_proj_dim=1_6_0						,    conv_in_kernel=1						,    conv_out_kernel=1						,    cross_attention_dim=3_2						,    down_block_types=(
										        "KDownBlock2D",
										        "KCrossAttnDownBlock2D",
										        "KCrossAttnDownBlock2D",
										        "KCrossAttnDownBlock2D",
										    )						,    in_channels=8						,    mid_block_type=__lowerCamelCase						,    only_cross_attention=__lowerCamelCase						,    out_channels=5						,    resnet_time_scale_shift="scale_shift"						,    time_embedding_type="fourier"						,    timestep_post_act="gelu"						,    up_block_types=("KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KUpBlock2D")						,    )
										__magic_name__            =     AutoencoderKL(
										    block_out_channels=[3_2, 3_2, 6_4, 6_4]						,    in_channels=3						,    out_channels=3						,    down_block_types=[
										        "DownEncoderBlock2D",
										        "DownEncoderBlock2D",
										        "DownEncoderBlock2D",
										        "DownEncoderBlock2D",
										    ]						,    up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]						,    latent_channels=4						,    )
										__magic_name__            =     EulerDiscreteScheduler(prediction_type="sample"	)
										__magic_name__            =     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="quick_gelu"						,    projection_dim=5_1_2						,    )
										__magic_name__            =     CLIPTextModel(__lowerCamelCase	)
										__magic_name__            =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

										__magic_name__            =     {
										    "unet": model.eval(),
										    "vae": vae.eval(),
										    "scheduler": scheduler,
										    "text_encoder": text_encoder,
										    "tokenizer": tokenizer,
										}

										return components







				def     _snake_case					(							self							:						Optional[int]						,    __lowerCamelCase							:						Optional[int]						,    __lowerCamelCase							:						Optional[int]=0	)				->					Dict:
										if str(__lowerCamelCase	).startswith("mps"	):
																__magic_name__            =     torch.manual_seed(__lowerCamelCase	)
										else:
																__magic_name__            =     torch.Generator(device=__lowerCamelCase	).manual_seed(__lowerCamelCase	)
										__magic_name__            =     {
										    "prompt": "A painting of a squirrel eating a burger",
										    "image": self.dummy_image.cpu(),
										    "generator": generator,
										    "num_inference_steps": 2,
										    "output_type": "numpy",
										}
										return inputs







				def     _snake_case					(							self							:						Tuple	)				->					Optional[int]:
										__magic_name__            =     "cpu"

										__magic_name__            =     self.get_dummy_components()
										__magic_name__            =     self.pipeline_class(**__lowerCamelCase	)
										pipe.to(__lowerCamelCase	)
										pipe.set_progress_bar_config(disable=__lowerCamelCase	)

										__magic_name__            =     self.get_dummy_inputs(__lowerCamelCase	)
										__magic_name__            =     pipe(**__lowerCamelCase	).images
										__magic_name__            =     image[0, -3:, -3:, -1]

										self.assertEqual(image.shape						,    (1, 2_5_6, 2_5_6, 3)	)
										__magic_name__            =     np.array(
										    [0.4722_2412, 0.4192_1633, 0.4471_7434, 0.4687_4192, 0.4258_8258, 0.4615_0726, 0.467_7534, 0.4558_3832, 0.4857_9055]	)
										__magic_name__            =     np.abs(image_slice.flatten() - expected_slice	).max()
										self.assertLessEqual(__lowerCamelCase						,    1e-3	)







				def     _snake_case					(							self							:						Dict	)				->					int:
										super().test_attention_slicing_forward_pass(expected_max_diff=7e-3	)







				def     _snake_case					(							self							:						List[str]	)				->					Any:
										super().test_cpu_offload_forward_pass(expected_max_diff=3e-3	)







				def     _snake_case					(							self							:						str	)				->					str:
										super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3	)







				def     _snake_case					(							self							:						Optional[Any]	)				->					Optional[Any]:
										super().test_inference_batch_single_identical(expected_max_diff=7e-3	)







				def     _snake_case					(							self							:						List[str]	)				->					Dict:
										super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3	)







				def     _snake_case					(							self							:						Any	)				->					Any:
										super().test_save_load_local(expected_max_difference=3e-3	)







				def     _snake_case					(							self							:						str	)				->					List[Any]:
										super().test_save_load_optional_components(expected_max_difference=3e-3	)







				def     _snake_case					(							self							:						Optional[Any]	)				->					Optional[int]:
										__magic_name__            =     [
										    "DDIMScheduler",
										    "DDPMScheduler",
										    "PNDMScheduler",
										    "HeunDiscreteScheduler",
										    "EulerAncestralDiscreteScheduler",
										    "KDPM2DiscreteScheduler",
										    "KDPM2AncestralDiscreteScheduler",
										    "DPMSolverSDEScheduler",
										]
										__magic_name__            =     self.get_dummy_components()
										__magic_name__            =     self.pipeline_class(**__lowerCamelCase	)

										# make sure that PNDM does not need warm-up
										pipe.scheduler.register_to_config(skip_prk_steps=__lowerCamelCase	)

										pipe.to(__lowerCamelCase	)
										pipe.set_progress_bar_config(disable=__lowerCamelCase	)
										__magic_name__            =     self.get_dummy_inputs(__lowerCamelCase	)
										__magic_name__            =     2

										__magic_name__            =     []
										for scheduler_enum in KarrasDiffusionSchedulers:
																if scheduler_enum.name in skip_schedulers:
																						# no sigma schedulers are not supported
																						# no schedulers
																						continue

																__magic_name__            =     getattr(__lowerCamelCase						,    scheduler_enum.name	)
																__magic_name__            =     scheduler_cls.from_config(pipe.scheduler.config	)
																__magic_name__            =     pipe(**__lowerCamelCase	)[0]
																outputs.append(__lowerCamelCase	)

										assert check_same_shape(__lowerCamelCase	)





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







				def     _snake_case					(							self							:						Tuple	)				->					Optional[int]:
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







				def     _snake_case					(							self							:						Dict	)				->					int:
										__magic_name__            =     torch.manual_seed(3_3	)

										__magic_name__            =     StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4"						,    torch_dtype=torch.floataa	)
										pipe.to("cuda"	)

										__magic_name__            =     StableDiffusionLatentUpscalePipeline.from_pretrained(
										    "stabilityai/sd-x2-latent-upscaler"						,    torch_dtype=torch.floataa	)
										upscaler.to("cuda"	)

										__magic_name__            =     "a photo of an astronaut high resolution, unreal engine, ultra realistic"

										__magic_name__            =     pipe(__lowerCamelCase						,    generator=__lowerCamelCase						,    output_type="latent"	).images

										__magic_name__            =     upscaler(
										    prompt=__lowerCamelCase						,    image=__lowerCamelCase						,    num_inference_steps=2_0						,    guidance_scale=0						,    generator=__lowerCamelCase						,    output_type="np"						,    ).images[0]

										__magic_name__            =     load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy"	)
										assert np.abs((expected_image - image).mean()	) < 5e-2







				def     _snake_case					(							self							:						Optional[int]	)				->					Union[str, Any]:
										__magic_name__            =     torch.manual_seed(3_3	)

										__magic_name__            =     StableDiffusionLatentUpscalePipeline.from_pretrained(
										    "stabilityai/sd-x2-latent-upscaler"						,    torch_dtype=torch.floataa	)
										upscaler.to("cuda"	)

										__magic_name__            =     "the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas"

										__magic_name__            =     load_image(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png"	)

										__magic_name__            =     upscaler(
										    prompt=__lowerCamelCase						,    image=__lowerCamelCase						,    num_inference_steps=2_0						,    guidance_scale=0						,    generator=__lowerCamelCase						,    output_type="np"						,    ).images[0]

										__magic_name__            =     load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy"	)
										assert np.abs((expected_image - image).max()	) < 5e-2











"""simple docstring"""

from copy import deepcopy

class 						A_							:







				def __init__(							self							:						List[str]						,    __lowerCamelCase							:						list[int] | None = None						,    __lowerCamelCase							:						int | None = None	)				->					None:

										if arr is None and size is not None:
																__magic_name__            =     size
																__magic_name__            =     [0] * size
										elif arr is not None:
																self.init(__lowerCamelCase	)
										else:
																raise ValueError("Either arr or size must be specified"	)







				def     _snake_case					(							self							:						Optional[int]						,    __lowerCamelCase							:						list[int]	)				->					None:
										__magic_name__            =     len(__lowerCamelCase	)
										__magic_name__            =     deepcopy(__lowerCamelCase	)
										for i in range(1						,    self.size	):
																__magic_name__            =     self.next_(__lowerCamelCase	)
																if j < self.size:
																						self.tree[j] += self.tree[i]







				def     _snake_case					(							self							:						Any	)				->					list[int]:
										__magic_name__            =     self.tree[:]
										for i in range(self.size - 1						,    0						,    -1	):
																__magic_name__            =     self.next_(__lowerCamelCase	)
																if j < self.size:
																						arr[j] -= arr[i]
										return arr







				@staticmethod
				def     _snake_case					(							__lowerCamelCase							:						int	)				->					int:
										return index + (index & (-index))







				@staticmethod
				def     _snake_case					(							__lowerCamelCase							:						int	)				->					int:
										return index - (index & (-index))







				def     _snake_case					(							self							:						Union[str, Any]						,    __lowerCamelCase							:						int						,    __lowerCamelCase							:						int	)				->					None:
										if index == 0:
																self.tree[0] += value
																return
										while index < self.size:
																self.tree[index] += value
																__magic_name__            =     self.next_(__lowerCamelCase	)







				def     _snake_case					(							self							:						Any						,    __lowerCamelCase							:						int						,    __lowerCamelCase							:						int	)				->					None:
										self.add(__lowerCamelCase						,    value - self.get(__lowerCamelCase	)	)







				def     _snake_case					(							self							:						List[Any]						,    __lowerCamelCase							:						int	)				->					int:
										if right == 0:
																return 0
										__magic_name__            =     self.tree[0]
										right -= 1  # make right inclusive
										while right > 0:
																result += self.tree[right]
																__magic_name__            =     self.prev(__lowerCamelCase	)
										return result







				def     _snake_case					(							self							:						Any						,    __lowerCamelCase							:						int						,    __lowerCamelCase							:						int	)				->					int:
										return self.prefix(__lowerCamelCase	) - self.prefix(__lowerCamelCase	)







				def     _snake_case					(							self							:						Tuple						,    __lowerCamelCase							:						int	)				->					int:
										return self.query(__lowerCamelCase						,    index + 1	)







				def     _snake_case					(							self							:						Tuple						,    __lowerCamelCase							:						int	)				->					int:
										value -= self.tree[0]
										if value < 0:
																return -1

										__magic_name__            =     1  # Largest power of 2 <= size
										while j * 2 < self.size:
																j *= 2

										__magic_name__            =     0

										while j > 0:
																if i + j < self.size and self.tree[i + j] <= value:
																						value -= self.tree[i + j]
																						i += j
																j //= 2
										return i


if __name__ == "__main__":
			import doctest

			doctest.testmod()



