


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





       '''simple docstring'''






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







       @property
       def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Optional[Any]:
              lowerCAmelCase__      =			1
              lowerCAmelCase__      =			3
              lowerCAmelCase__      =			(32, 32)

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







       @property
       def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Any:
              torch.manual_seed(0     )
              lowerCAmelCase__      =			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 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Union[str, Any]:
              torch.manual_seed(0     )
              lowerCAmelCase__      =			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 						__SCREAMING_SNAKE_CASE							(	self     ) ->							str:
              torch.manual_seed(0     )
              lowerCAmelCase__      =			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=50_06      ,					)
              return RobertaSeriesModelWithTransformation(lowerCAmelCase__     )







       @property
       def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Any:
              def extract(*lowerCamelCase_      ,					**lowerCamelCase_     ):




                     class 	a__       :





                            '''simple docstring'''






                            def __init__(	self     ) ->							Optional[Any]:
                                   lowerCAmelCase__      =			torch.ones([0]     )







                            def 						__SCREAMING_SNAKE_CASE							(	self      ,					lowerCamelCase_     ) ->							Optional[Any]:
                                   self.pixel_values.to(lowerCAmelCase__     )
                                   return self

                     return Out()

              return extract







       def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[Any]:
              lowerCAmelCase__      =			"cpu"  # ensure determinism for the device-dependent torch.Generator
              lowerCAmelCase__      =			self.dummy_cond_unet
              lowerCAmelCase__      =			PNDMScheduler(skip_prk_steps=lowerCAmelCase__     )
              lowerCAmelCase__      =			self.dummy_vae
              lowerCAmelCase__      =			self.dummy_text_encoder
              lowerCAmelCase__      =			XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''     )
              lowerCAmelCase__      =			77

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

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

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

              lowerCAmelCase__      =			output.images

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

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

              assert image.shape == (1, 32, 32, 3)
              lowerCAmelCase__      =			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 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[str]:
              lowerCAmelCase__      =			self.dummy_cond_unet
              lowerCAmelCase__      =			PNDMScheduler(skip_prk_steps=lowerCAmelCase__     )
              lowerCAmelCase__      =			self.dummy_vae
              lowerCAmelCase__      =			self.dummy_text_encoder
              lowerCAmelCase__      =			XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''     )
              lowerCAmelCase__      =			77

              lowerCAmelCase__      =			self.dummy_image.to(lowerCAmelCase__     )

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

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

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

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







       @unittest.skipIf(torch_device != '''cuda'''      ,					'''This test requires a GPU'''     )
       def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							List[Any]:
              lowerCAmelCase__      =			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
              lowerCAmelCase__      =			init_image.resize((7_60, 5_04)     )

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

              lowerCAmelCase__      =			"A fantasy landscape, trending on artstation"

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

              lowerCAmelCase__      =			image[2_55:2_58, 3_83:3_86, -1]

              assert image.shape == (5_04, 7_60, 3)
              lowerCAmelCase__      =			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 	a__       (							unittest.TestCase						):





       '''simple docstring'''






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







       def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							Optional[int]:
              lowerCAmelCase__      =			load_image(
                  '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                  '''/img2img/sketch-mountains-input.jpg'''     )
              lowerCAmelCase__      =			init_image.resize((7_68, 5_12)     )
              lowerCAmelCase__      =			load_numpy(
                  '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'''     )

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

              lowerCAmelCase__      =			"A fantasy landscape, trending on artstation"

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

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



'''simple docstring'''






import doctest
from collections import deque

import numpy as np




class 	a__       :





							'''simple docstring'''






							def __init__(	self     ) ->							None:
														lowerCAmelCase__      =			[2, 1, 2, -1]
														lowerCAmelCase__      =			[1, 2, 3, 4]







							def 						__SCREAMING_SNAKE_CASE							(	self     ) ->							list[float]:
														lowerCAmelCase__      =			len(self.first_signal     )
														lowerCAmelCase__      =			len(self.second_signal     )

														lowerCAmelCase__      =			max(lowerCamelCase_      ,					lowerCamelCase_     )

														# create a zero matrix of max_length x max_length
														lowerCAmelCase__      =			[[0] * max_length for i in range(lowerCamelCase_     )]

														# fills the smaller signal with zeros to make both signals of same length
														if length_first_signal < length_second_signal:
																					self.first_signal += [0] * (max_length - length_first_signal)
														elif length_first_signal > length_second_signal:
																					self.second_signal += [0] * (max_length - length_second_signal)
														for i in range(lowerCamelCase_     ):
																					lowerCAmelCase__      =			deque(self.second_signal     )
																					rotated_signal.rotate(lowerCamelCase_     )
																					for j, item in enumerate(lowerCamelCase_     ):
																												matrix[i][j] += item

        # multiply the matrix with the first signal
														lowerCAmelCase__      =			np.matmul(np.transpose(lowerCamelCase_     )      ,					np.transpose(self.first_signal     )     )

														# rounding-off to two decimal places
														return [round(lowerCamelCase_      ,					2     ) for i in final_signal]


if __name__ == "__main__":
		doctest.testmod()