


"""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       ):




		'''simple docstring'''







		def 				__A		(      self							)	->				int:
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()







		@property
		def 				__A		(      self							)	->				Optional[int]:
								SCREAMING_SNAKE_CASE						=   1
								SCREAMING_SNAKE_CASE						=   3
								SCREAMING_SNAKE_CASE						=   (32, 32)

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







		@property
		def 				__A		(      self							)	->				Any:
								torch.manual_seed(0							)
								SCREAMING_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 				__A		(      self							)	->				Tuple:
								torch.manual_seed(0							)
								SCREAMING_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 				__A		(      self							)	->				Tuple:
								torch.manual_seed(0							)
								SCREAMING_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=5_006		,			)
								return RobertaSeriesModelWithTransformation(_lowercase							)







		@property
		def 				__A		(      self							)	->				List[str]:
								def extract(*lowerCAmelCase__		,			**lowerCAmelCase__							):
														class    lowerCAmelCase      :




																'''simple docstring'''







																def __init__(      self							)	->				Dict:
																						SCREAMING_SNAKE_CASE						=   torch.ones([0]							)







																def 				__A		(      self		,			lowerCAmelCase__							)	->				List[str]:
																						self.pixel_values.to(_lowercase							)
																						return self





														return Out()

								return extract







		def 				__A		(      self							)	->				Tuple:
								SCREAMING_SNAKE_CASE						=   'cpu'  # ensure determinism for the device-dependent torch.Generator
								SCREAMING_SNAKE_CASE						=   self.dummy_cond_unet
								SCREAMING_SNAKE_CASE						=   PNDMScheduler(skip_prk_steps=_lowercase							)
								SCREAMING_SNAKE_CASE						=   self.dummy_vae
								SCREAMING_SNAKE_CASE						=   self.dummy_text_encoder
								SCREAMING_SNAKE_CASE						=   XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'							)
								SCREAMING_SNAKE_CASE						=   77

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

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

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

								SCREAMING_SNAKE_CASE						=   output.images

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

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

								assert image.shape == (1, 32, 32, 3)
								SCREAMING_SNAKE_CASE						=   np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]							)

								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 				__A		(      self							)	->				str:
								SCREAMING_SNAKE_CASE						=   self.dummy_cond_unet
								SCREAMING_SNAKE_CASE						=   PNDMScheduler(skip_prk_steps=_lowercase							)
								SCREAMING_SNAKE_CASE						=   self.dummy_vae
								SCREAMING_SNAKE_CASE						=   self.dummy_text_encoder
								SCREAMING_SNAKE_CASE						=   XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'							)
								SCREAMING_SNAKE_CASE						=   77

								SCREAMING_SNAKE_CASE						=   self.dummy_image.to(_lowercase							)

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

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

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

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







		@unittest.skipIf(torch_device != 'cuda'		,			'This test requires a GPU'							)
		def 				__A		(      self							)	->				Optional[Any]:
								SCREAMING_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
								SCREAMING_SNAKE_CASE						=   init_image.resize((760, 504)							)

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

								SCREAMING_SNAKE_CASE						=   'A fantasy landscape, trending on artstation'

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

								SCREAMING_SNAKE_CASE						=   image[255:258, 383:386, -1]

								assert image.shape == (504, 760, 3)
								SCREAMING_SNAKE_CASE						=   np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]							)

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





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




		'''simple docstring'''







		def 				__A		(      self							)	->				List[Any]:
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()







		def 				__A		(      self							)	->				Optional[int]:
								SCREAMING_SNAKE_CASE						=   load_image(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
								    '/img2img/sketch-mountains-input.jpg'							)
								SCREAMING_SNAKE_CASE						=   init_image.resize((768, 512)							)
								SCREAMING_SNAKE_CASE						=   load_numpy(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'							)

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

								SCREAMING_SNAKE_CASE						=   'A fantasy landscape, trending on artstation'

								SCREAMING_SNAKE_CASE						=   torch.manual_seed(0							)
								SCREAMING_SNAKE_CASE						=   pipe(
								    prompt=_lowercase		,			image=_lowercase		,			strength=0.75		,			guidance_scale=7.5		,			generator=_lowercase		,			output_type='np'		,			)
								SCREAMING_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





'''simple docstring'''

def 							_UpperCamelCase				(   lowerCAmelCase__:					int		,lowerCAmelCase__:					int   )      -> str:
							if a < 0 or b < 0:
														raise ValueError('the value of both inputs must be positive'   )
							SCREAMING_SNAKE_CASE_				=				str(bin(lowerCAmelCase__   )   )[2:]  # remove the leading "0b"
							SCREAMING_SNAKE_CASE_				=				str(bin(lowerCAmelCase__   )   )[2:]
							SCREAMING_SNAKE_CASE_				=				max(len(lowerCAmelCase__   )		,len(lowerCAmelCase__   )   )
							return "0b" + "".join(
							    str(int('1' in (char_a, char_b)   )   )
							    for char_a, char_b in zip(a_binary.zfill(lowerCAmelCase__   )		,b_binary.zfill(lowerCAmelCase__   )   )   )


if __name__ == "__main__":
							import doctest

							doctest.testmod()





