




'''simple docstring'''



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      lowerCAmelCase (			unittest.TestCase):


       def    lowerCAmelCase   ( self	)   ->	Optional[Any]:



            '''simple docstring'''




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


       @property
       def    lowerCAmelCase   ( self	)   ->	int:



            '''simple docstring'''




            __snake_case            =	1
            __snake_case            =	3
            __snake_case            =	(32, 32)

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


       @property
       def    lowerCAmelCase   ( self	)   ->	str:



            '''simple docstring'''




            torch.manual_seed(0	)
            __snake_case            =	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    lowerCAmelCase   ( self	)   ->	Optional[int]:



            '''simple docstring'''




            torch.manual_seed(0	)
            __snake_case            =	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    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            torch.manual_seed(0	)
            __snake_case            =	RobertaSeriesConfig(
                hidden_size=32     ,	project_dim=32     ,	intermediate_size=37     ,	layer_norm_eps=1E-05     ,	num_attention_heads=4     ,	num_hidden_layers=5     ,	pad_token_id=1     ,	vocab_size=5006     ,	)
            return RobertaSeriesModelWithTransformation(SCREAMING_SNAKE_CASE_	)


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



            '''simple docstring'''




            def extract(*__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE	):





                 class      lowerCAmelCase :


                        def __init__( self	)   ->	Tuple:



                             '''simple docstring'''




                             __snake_case            =	torch.ones([0]	)




                        def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE	)   ->	List[Any]:



                             '''simple docstring'''




                             self.pixel_values.to(SCREAMING_SNAKE_CASE_	)
                             return self





                 return Out()

            return extract


       def    lowerCAmelCase   ( self	)   ->	int:



            '''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            =	77

            __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, 32, 32, 3)
            __snake_case            =	np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499]	)

            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    lowerCAmelCase   ( self	)   ->	str:



            '''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            =	77

            __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, 32, 32, 3)




       @unittest.skipIf(torch_device != '''cuda'''     ,	'''This test requires a GPU'''	)
       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''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((760, 504)	)

            __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[255:258, 383:386, -1]

            assert image.shape == (504, 760, 3)
            __snake_case            =	np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000]	)

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





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


       def    lowerCAmelCase   ( self	)   ->	int:



            '''simple docstring'''




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




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



            '''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((768, 512)	)
            __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 == (512, 768, 3)
            # img2img is flaky across GPUs even in fp32, so using MAE here
            assert np.abs(expected_image - image	).max() < 1E-2











def  lowerCAmelCase_	(lowerCAmelCase__:		Union[str, Any]		,						lowerCAmelCase__:		Optional[int]  ):





			"""simple docstring"""


			UpperCAmelCase_:		List[str]							      =     0
			UpperCAmelCase_:		Tuple							      =     len(lowerCAmelCase__  ) - 1

			while left <= right:
						# avoid divided by 0 during interpolation
						if sorted_collection[left] == sorted_collection[right]:
									if sorted_collection[left] == item:
												return left
									else:
												return None

						UpperCAmelCase_:		Dict							      =     left + ((item - sorted_collection[left]) * (right - left)) // (
						    sorted_collection[right] - sorted_collection[left]
						)

						# out of range check
						if point < 0 or point >= len(lowerCAmelCase__  ):
									return None

						UpperCAmelCase_:		str							      =     sorted_collection[point]
						if current_item == item:
									return point
						else:
									if point < left:
												UpperCAmelCase_:		int							      =     left
												UpperCAmelCase_:		str							      =     point
									elif point > right:
												UpperCAmelCase_:		List[str]							      =     right
												UpperCAmelCase_:		Optional[int]							      =     point
									else:
												if item < current_item:
															UpperCAmelCase_:		Optional[Any]							      =     point - 1
												else:
															UpperCAmelCase_:		Any							      =     point + 1
			return None







def  lowerCAmelCase_	(lowerCAmelCase__:		Dict		,						lowerCAmelCase__:		List[Any]		,						lowerCAmelCase__:		Any		,						lowerCAmelCase__:		Any  ):





			"""simple docstring"""


			if sorted_collection[left] == sorted_collection[right]:
						if sorted_collection[left] == item:
									return left
						else:
									return None

			UpperCAmelCase_:		Union[str, Any]							      =     left + ((item - sorted_collection[left]) * (right - left)) // (
			    sorted_collection[right] - sorted_collection[left]
			)

			# out of range check
			if point < 0 or point >= len(lowerCAmelCase__  ):
						return None

			if sorted_collection[point] == item:
						return point
			elif point < left:
						return interpolation_search_by_recursion(lowerCAmelCase__		,						lowerCAmelCase__		,						lowerCAmelCase__		,						lowerCAmelCase__  )
			elif point > right:
						return interpolation_search_by_recursion(lowerCAmelCase__		,						lowerCAmelCase__		,						lowerCAmelCase__		,						lowerCAmelCase__  )
			else:
						if sorted_collection[point] > item:
									return interpolation_search_by_recursion(
									    lowerCAmelCase__		,						lowerCAmelCase__		,						lowerCAmelCase__		,						point - 1  )
						else:
									return interpolation_search_by_recursion(
									    lowerCAmelCase__		,						lowerCAmelCase__		,						point + 1		,						lowerCAmelCase__  )







def  lowerCAmelCase_	(lowerCAmelCase__:		Dict  ):





			"""simple docstring"""


			if collection != sorted(lowerCAmelCase__  ):
						raise ValueError("""Collection must be ascending sorted"""  )
			return True


if __name__ == "__main__":
	import sys
	a      :  Optional[Any]			     =			0
	if debug == 1:
		a      :  int			     =			[10, 30, 40, 45, 50, 66, 77, 93]
		try:
			__assert_sorted(collection)
		except ValueError:
			sys.exit('Sequence must be ascending sorted to apply interpolation search')
		a      :  int			     =			67

	a      :  Any			     =			interpolation_search(collection, target)
	if result is not None:
		print(F'''{target} found at positions: {result}''')
	else:
		print('Not found')






