


import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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


enable_full_determinism()






class     UpperCamelCase(  unittest.TestCase   ):


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]						)			->	Optional[int]:




											'''simple docstring'''

											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]						)			->	Optional[Any]:




											'''simple docstring'''

											__snake_case				=		1
											__snake_case				=		3
											__snake_case				=		(3_2, 3_2)

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


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]						)			->	Tuple:




											'''simple docstring'''

											torch.manual_seed(0						)
											__snake_case				=		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")     ,    cross_attention_dim=3_2     ,    )
											return model


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]						)			->	Any:




											'''simple docstring'''

											torch.manual_seed(0						)
											__snake_case				=		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     ,    )
											return model


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		Union[str, Any]						)			->	List[str]:




											'''simple docstring'''

											torch.manual_seed(0						)
											__snake_case				=		RobertaSeriesConfig(
											    hidden_size=3_2     ,    project_dim=3_2     ,    intermediate_size=3_7     ,    layer_norm_eps=1e-0_5     ,    num_attention_heads=4     ,    num_hidden_layers=5     ,    pad_token_id=1     ,    vocab_size=5_0_0_6     ,    )
											return RobertaSeriesModelWithTransformation(SCREAMING_SNAKE_CASE						)


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		Dict						)			->	List[Any]:




											'''simple docstring'''

											def extract(*SCREAMING_SNAKE_CASE	:		Any     ,    **SCREAMING_SNAKE_CASE	:		str						):






																	class     UpperCamelCase:


																						def __init__(						self	:		Tuple						)			->	List[Any]:




																												'''simple docstring'''

																												__snake_case				=		torch.ones([0]						)






																						def 							SCREAMING_SNAKE_CASE_  (						self	:		Any     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]						)			->	int:




																												'''simple docstring'''

																												self.pixel_values.to(SCREAMING_SNAKE_CASE						)
																												return self




																	return Out()

											return extract


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Tuple						)			->	List[str]:




											'''simple docstring'''

											__snake_case				=		"cpu"  # ensure determinism for the device-dependent torch.Generator
											__snake_case				=		self.dummy_cond_unet
											__snake_case				=		PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE						)
											__snake_case				=		self.dummy_vae
											__snake_case				=		self.dummy_text_encoder
											__snake_case				=		XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"						)
											__snake_case				=		7_7

											__snake_case				=		self.dummy_image.to(SCREAMING_SNAKE_CASE						)
											__snake_case				=		init_image / 2 + 0.5

											# make sure here that pndm scheduler skips prk
											__snake_case				=		AltDiffusionImgaImgPipeline(
											    unet=SCREAMING_SNAKE_CASE     ,    scheduler=SCREAMING_SNAKE_CASE     ,    vae=SCREAMING_SNAKE_CASE     ,    text_encoder=SCREAMING_SNAKE_CASE     ,    tokenizer=SCREAMING_SNAKE_CASE     ,    safety_checker=SCREAMING_SNAKE_CASE     ,    feature_extractor=self.dummy_extractor     ,    )
											__snake_case				=		VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor     ,    do_normalize=SCREAMING_SNAKE_CASE						)
											__snake_case				=		alt_pipe.to(SCREAMING_SNAKE_CASE						)
											alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		"A painting of a squirrel eating a burger"
											__snake_case				=		torch.Generator(device=SCREAMING_SNAKE_CASE						).manual_seed(0						)
											__snake_case				=		alt_pipe(
											    [prompt]     ,    generator=SCREAMING_SNAKE_CASE     ,    guidance_scale=6.0     ,    num_inference_steps=2     ,    output_type="np"     ,    image=SCREAMING_SNAKE_CASE     ,    )

											__snake_case				=		output.images

											__snake_case				=		torch.Generator(device=SCREAMING_SNAKE_CASE						).manual_seed(0						)
											__snake_case				=		alt_pipe(
											    [prompt]     ,    generator=SCREAMING_SNAKE_CASE     ,    guidance_scale=6.0     ,    num_inference_steps=2     ,    output_type="np"     ,    image=SCREAMING_SNAKE_CASE     ,    return_dict=SCREAMING_SNAKE_CASE     ,    )[0]

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

											assert image.shape == (1, 3_2, 3_2, 3)
											__snake_case				=		np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]						)

											assert np.abs(image_slice.flatten() - expected_slice						).max() < 5e-3
											assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 5e-3


					@unittest.skipIf(torch_device != "cuda"     ,    "This test requires a GPU"						)
					def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[Any]						)			->	Union[str, Any]:




											'''simple docstring'''

											__snake_case				=		self.dummy_cond_unet
											__snake_case				=		PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE						)
											__snake_case				=		self.dummy_vae
											__snake_case				=		self.dummy_text_encoder
											__snake_case				=		XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"						)
											__snake_case				=		7_7

											__snake_case				=		self.dummy_image.to(SCREAMING_SNAKE_CASE						)

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

											# make sure here that pndm scheduler skips prk
											__snake_case				=		AltDiffusionImgaImgPipeline(
											    unet=SCREAMING_SNAKE_CASE     ,    scheduler=SCREAMING_SNAKE_CASE     ,    vae=SCREAMING_SNAKE_CASE     ,    text_encoder=SCREAMING_SNAKE_CASE     ,    tokenizer=SCREAMING_SNAKE_CASE     ,    safety_checker=SCREAMING_SNAKE_CASE     ,    feature_extractor=self.dummy_extractor     ,    )
											__snake_case				=		VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor     ,    do_normalize=SCREAMING_SNAKE_CASE						)
											__snake_case				=		alt_pipe.to(SCREAMING_SNAKE_CASE						)
											alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		"A painting of a squirrel eating a burger"
											__snake_case				=		torch.manual_seed(0						)
											__snake_case				=		alt_pipe(
											    [prompt]     ,    generator=SCREAMING_SNAKE_CASE     ,    num_inference_steps=2     ,    output_type="np"     ,    image=SCREAMING_SNAKE_CASE     ,    ).images

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






					@unittest.skipIf(torch_device != "cuda"     ,    "This test requires a GPU"						)
					def 							SCREAMING_SNAKE_CASE_  (						self	:		Union[str, Any]						)			->	int:




											'''simple docstring'''

											__snake_case				=		load_image(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
											    "/img2img/sketch-mountains-input.jpg"						)
											# resize to resolution that is divisible by 8 but not 16 or 32
											__snake_case				=		init_image.resize((7_6_0, 5_0_4)						)

											__snake_case				=		"BAAI/AltDiffusion"
											__snake_case				=		AltDiffusionImgaImgPipeline.from_pretrained(
											    SCREAMING_SNAKE_CASE     ,    safety_checker=SCREAMING_SNAKE_CASE     ,    )
											pipe.to(SCREAMING_SNAKE_CASE						)
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)
											pipe.enable_attention_slicing()

											__snake_case				=		"A fantasy landscape, trending on artstation"

											__snake_case				=		torch.manual_seed(0						)
											__snake_case				=		pipe(
											    prompt=SCREAMING_SNAKE_CASE     ,    image=SCREAMING_SNAKE_CASE     ,    strength=0.75     ,    guidance_scale=7.5     ,    generator=SCREAMING_SNAKE_CASE     ,    output_type="np"     ,    )
											__snake_case				=		output.images[0]

											__snake_case				=		image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

											assert image.shape == (5_0_4, 7_6_0, 3)
											__snake_case				=		np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]						)

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






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


					def 							SCREAMING_SNAKE_CASE_  (						self	:		int						)			->	Any:




											'''simple docstring'''

											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






					def 							SCREAMING_SNAKE_CASE_  (						self	:		Union[str, Any]						)			->	Dict:




											'''simple docstring'''

											__snake_case				=		load_image(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
											    "/img2img/sketch-mountains-input.jpg"						)
											__snake_case				=		init_image.resize((7_6_8, 5_1_2)						)
											__snake_case				=		load_numpy(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"						)

											__snake_case				=		"BAAI/AltDiffusion"
											__snake_case				=		AltDiffusionImgaImgPipeline.from_pretrained(
											    SCREAMING_SNAKE_CASE     ,    safety_checker=SCREAMING_SNAKE_CASE     ,    )
											pipe.to(SCREAMING_SNAKE_CASE						)
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)
											pipe.enable_attention_slicing()

											__snake_case				=		"A fantasy landscape, trending on artstation"

											__snake_case				=		torch.manual_seed(0						)
											__snake_case				=		pipe(
											    prompt=SCREAMING_SNAKE_CASE     ,    image=SCREAMING_SNAKE_CASE     ,    strength=0.75     ,    guidance_scale=7.5     ,    generator=SCREAMING_SNAKE_CASE     ,    output_type="np"     ,    )
											__snake_case				=		output.images[0]

											assert image.shape == (5_1_2, 7_6_8, 3)
											# img2img is flaky across GPUs even in fp32, so using MAE here
											assert np.abs(expected_image - image						).max() < 1e-2









from __future__ import annotations





def 	_lowerCAmelCase       (    _lowerCAmelCase )						->	list:


						'''simple docstring'''






						if len(_lowerCAmelCase ) == 0:
												return []
						__snake_case		,					__snake_case				=		min(_lowerCAmelCase ), max(_lowerCAmelCase )
						__snake_case				=		int(max_value - min_value ) + 1
						__snake_case				=		[[] for _ in range(_lowerCAmelCase )]

						for i in my_list:
												buckets[int(i - min_value )].append(_lowerCAmelCase )

						return [v for bucket in buckets for v in sorted(_lowerCAmelCase )]


if __name__ == "__main__":
	from doctest import testmod

	testmod()
	assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
	assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]





