


import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModelWithProjection

from diffusers import (
    AutoencoderKL,
    DPMSolverMultistepScheduler,
    PNDMScheduler,
    StableDiffusionImageVariationPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class   __lowerCamelCase (_a							,			_a							,			_a							,			unittest.TestCase	):
       _lowercase       							=    StableDiffusionImageVariationPipeline
       _lowercase       							=    IMAGE_VARIATION_PARAMS
       _lowercase       							=    IMAGE_VARIATION_BATCH_PARAMS
       _lowercase       							=    frozenset([]	)
       # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
       _lowercase       							=    frozenset([]	)







       def 		snake_case_  ( self:   List[str]				):






            '''simple docstring'''




            torch.manual_seed(0				)
            __UpperCamelCase   = 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,)
            __UpperCamelCase   = PNDMScheduler(skip_prk_steps=A_				)
            torch.manual_seed(0				)
            __UpperCamelCase   = 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,)
            torch.manual_seed(0				)
            __UpperCamelCase   = CLIPVisionConfig(
                hidden_size=32,projection_dim=32,intermediate_size=37,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,image_size=32,patch_size=4,)
            __UpperCamelCase   = CLIPVisionModelWithProjection(A_				)
            __UpperCamelCase   = CLIPImageProcessor(crop_size=32,size=32				)

            __UpperCamelCase   = {
                'unet': unet,
                'scheduler': scheduler,
                'vae': vae,
                'image_encoder': image_encoder,
                'feature_extractor': feature_extractor,
                'safety_checker': None,
            }
            return components







       def 		snake_case_  ( self:   List[Any],A_:   Tuple,A_:   Tuple=0				):






            '''simple docstring'''




            __UpperCamelCase   = floats_tensor((1, 3, 32, 32),rng=random.Random(A_				)				)
            __UpperCamelCase   = image.cpu().permute(0,2,3,1				)[0]
            __UpperCamelCase   = Image.fromarray(np.uinta(A_				)				).convert('RGB'				).resize((32, 32)				)
            if str(A_				).startswith('mps'				):
                 __UpperCamelCase   = torch.manual_seed(A_				)
            else:
                 __UpperCamelCase   = torch.Generator(device=A_				).manual_seed(A_				)
            __UpperCamelCase   = {
                'image': image,
                'generator': generator,
                'num_inference_steps': 2,
                'guidance_scale': 6.0,
                'output_type': 'numpy',
            }
            return inputs







       def 		snake_case_  ( self:   str				):






            '''simple docstring'''




            __UpperCamelCase   = 'cpu'  # ensure determinism for the device-dependent torch.Generator
            __UpperCamelCase   = self.get_dummy_components()
            __UpperCamelCase   = StableDiffusionImageVariationPipeline(**A_				)
            __UpperCamelCase   = sd_pipe.to(A_				)
            sd_pipe.set_progress_bar_config(disable=A_				)

            __UpperCamelCase   = self.get_dummy_inputs(A_				)
            __UpperCamelCase   = sd_pipe(**A_				).images
            __UpperCamelCase   = image[0, -3:, -3:, -1]

            assert image.shape == (1, 64, 64, 3)
            __UpperCamelCase   = np.array([0.5_2_3_9, 0.5_7_2_3, 0.4_7_9_6, 0.5_0_4_9, 0.5_5_5_0, 0.4_6_8_5, 0.5_3_2_9, 0.4_8_9_1, 0.4_9_2_1]				)

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







       def 		snake_case_  ( self:   Any				):






            '''simple docstring'''




            __UpperCamelCase   = 'cpu'  # ensure determinism for the device-dependent torch.Generator
            __UpperCamelCase   = self.get_dummy_components()
            __UpperCamelCase   = StableDiffusionImageVariationPipeline(**A_				)
            __UpperCamelCase   = sd_pipe.to(A_				)
            sd_pipe.set_progress_bar_config(disable=A_				)

            __UpperCamelCase   = self.get_dummy_inputs(A_				)
            __UpperCamelCase   = 2 * [inputs['image']]
            __UpperCamelCase   = sd_pipe(**A_				)

            __UpperCamelCase   = output.images

            __UpperCamelCase   = image[-1, -3:, -3:, -1]

            assert image.shape == (2, 64, 64, 3)
            __UpperCamelCase   = np.array([0.6_8_9_2, 0.5_6_3_7, 0.5_8_3_6, 0.5_7_7_1, 0.6_2_5_4, 0.6_4_0_9, 0.5_5_8_0, 0.5_5_6_9, 0.5_2_8_9]				)

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







       def 		snake_case_  ( self:   Tuple				):






            '''simple docstring'''




            super().test_inference_batch_single_identical(expected_max_diff=3E-3				)



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







       def 		snake_case_  ( self:   Any				):






            '''simple docstring'''




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







       def 		snake_case_  ( self:   List[Any],A_:   Any,A_:   Optional[int]="cpu",A_:   Any=torch.floataa,A_:   Tuple=0				):






            '''simple docstring'''




            __UpperCamelCase   = torch.Generator(device=A_				).manual_seed(A_				)
            __UpperCamelCase   = load_image(
                'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
                '/stable_diffusion_imgvar/input_image_vermeer.png'				)
            __UpperCamelCase   = np.random.RandomState(A_				).standard_normal((1, 4, 64, 64)				)
            __UpperCamelCase   = torch.from_numpy(A_				).to(device=A_,dtype=A_				)
            __UpperCamelCase   = {
                'image': init_image,
                'latents': latents,
                'generator': generator,
                'num_inference_steps': 3,
                'guidance_scale': 7.5,
                'output_type': 'numpy',
            }
            return inputs







       def 		snake_case_  ( self:   str				):






            '''simple docstring'''




            __UpperCamelCase   = StableDiffusionImageVariationPipeline.from_pretrained(
                'lambdalabs/sd-image-variations-diffusers',safety_checker=A_				)
            __UpperCamelCase   = sd_pipe.to(A_				)
            sd_pipe.set_progress_bar_config(disable=A_				)

            __UpperCamelCase   = self.get_inputs(A_				)
            __UpperCamelCase   = sd_pipe(**A_				).images
            __UpperCamelCase   = image[0, -3:, -3:, -1].flatten()

            assert image.shape == (1, 512, 512, 3)
            __UpperCamelCase   = np.array([0.8_4_4_9_1, 0.9_0_7_8_9, 0.7_5_7_0_8, 0.7_8_7_3_4, 0.8_3_4_8_5, 0.7_0_0_9_9, 0.6_6_9_3_8, 0.6_8_7_2_7, 0.6_1_3_7_9]				)
            assert np.abs(image_slice - expected_slice				).max() < 6E-3







       def 		snake_case_  ( self:   str				):






            '''simple docstring'''




            __UpperCamelCase   = 0

            def callback_fn(A_:   int,A_:   int,A_:   torch.FloatTensor				) -> None:
                 __UpperCamelCase   = True
                 nonlocal number_of_steps
                 number_of_steps += 1
                 if step == 1:
                      __UpperCamelCase   = latents.detach().cpu().numpy()
                      assert latents.shape == (1, 4, 64, 64)
                      __UpperCamelCase   = latents[0, -3:, -3:, -1]
                      __UpperCamelCase   = np.array(
                          [-0.1_6_2_1, 0.2_8_3_7, -0.7_9_7_9, -0.1_2_2_1, -1.3_0_5_7, 0.7_6_8_1, -2.1_1_9_1, 0.0_4_6_4, 1.6_3_0_9]				)

                      assert np.abs(latents_slice.flatten() - expected_slice				).max() < 5E-2
                 elif step == 2:
                      __UpperCamelCase   = latents.detach().cpu().numpy()
                      assert latents.shape == (1, 4, 64, 64)
                      __UpperCamelCase   = latents[0, -3:, -3:, -1]
                      __UpperCamelCase   = np.array([0.6_2_9_9, 1.7_5_0_0, 1.1_9_9_2, -2.1_5_8_2, -1.8_9_9_4, 0.7_3_3_4, -0.7_0_9_0, 1.0_1_3_7, 1.5_2_7_3]				)

                      assert np.abs(latents_slice.flatten() - expected_slice				).max() < 5E-2

            __UpperCamelCase   = False

            __UpperCamelCase   = StableDiffusionImageVariationPipeline.from_pretrained(
                'fusing/sd-image-variations-diffusers',safety_checker=A_,torch_dtype=torch.floataa,)
            pipe.to(A_				)
            pipe.set_progress_bar_config(disable=A_				)
            pipe.enable_attention_slicing()

            __UpperCamelCase   = self.get_inputs(A_,dtype=torch.floataa				)
            pipe(**A_,callback=A_,callback_steps=1				)
            assert callback_fn.has_been_called
            assert number_of_steps == inputs["num_inference_steps"]







       def 		snake_case_  ( self:   Optional[Any]				):






            '''simple docstring'''




            torch.cuda.empty_cache()
            torch.cuda.reset_max_memory_allocated()
            torch.cuda.reset_peak_memory_stats()

            __UpperCamelCase   = 'fusing/sd-image-variations-diffusers'
            __UpperCamelCase   = StableDiffusionImageVariationPipeline.from_pretrained(
                A_,safety_checker=A_,torch_dtype=torch.floataa				)
            __UpperCamelCase   = pipe.to(A_				)
            pipe.set_progress_bar_config(disable=A_				)
            pipe.enable_attention_slicing(1				)
            pipe.enable_sequential_cpu_offload()

            __UpperCamelCase   = self.get_inputs(A_,dtype=torch.floataa				)
            __UpperCamelCase   = pipe(**A_				)

            __UpperCamelCase   = torch.cuda.max_memory_allocated()
            # make sure that less than 2.6 GB is allocated
            assert mem_bytes < 2.6 * 10**9



@nightly
@require_torch_gpu
class   __lowerCamelCase (unittest.TestCase	):







       def 		snake_case_  ( self:   Optional[int]				):






            '''simple docstring'''




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







       def 		snake_case_  ( self:   Optional[Any],A_:   List[Any],A_:   str="cpu",A_:   Dict=torch.floataa,A_:   Optional[int]=0				):






            '''simple docstring'''




            __UpperCamelCase   = torch.Generator(device=A_				).manual_seed(A_				)
            __UpperCamelCase   = load_image(
                'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
                '/stable_diffusion_imgvar/input_image_vermeer.png'				)
            __UpperCamelCase   = np.random.RandomState(A_				).standard_normal((1, 4, 64, 64)				)
            __UpperCamelCase   = torch.from_numpy(A_				).to(device=A_,dtype=A_				)
            __UpperCamelCase   = {
                'image': init_image,
                'latents': latents,
                'generator': generator,
                'num_inference_steps': 50,
                'guidance_scale': 7.5,
                'output_type': 'numpy',
            }
            return inputs







       def 		snake_case_  ( self:   Any				):






            '''simple docstring'''




            __UpperCamelCase   = StableDiffusionImageVariationPipeline.from_pretrained('fusing/sd-image-variations-diffusers'				)
            sd_pipe.to(A_				)
            sd_pipe.set_progress_bar_config(disable=A_				)

            __UpperCamelCase   = self.get_inputs(A_				)
            __UpperCamelCase   = sd_pipe(**A_				).images[0]

            __UpperCamelCase   = load_numpy(
                'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
                '/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy'				)
            __UpperCamelCase   = np.abs(expected_image - image				).max()
            assert max_diff < 1E-3







       def 		snake_case_  ( self:   List[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = StableDiffusionImageVariationPipeline.from_pretrained('fusing/sd-image-variations-diffusers'				)
            __UpperCamelCase   = DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config				)
            sd_pipe.to(A_				)
            sd_pipe.set_progress_bar_config(disable=A_				)

            __UpperCamelCase   = self.get_inputs(A_				)
            __UpperCamelCase   = 25
            __UpperCamelCase   = sd_pipe(**A_				).images[0]

            __UpperCamelCase   = load_numpy(
                'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
                '/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy'				)
            __UpperCamelCase   = np.abs(expected_image - image				).max()
            assert max_diff < 1E-3






def 		_A		(		_lowercase   )				->   bool:


     """simple docstring"""


     if not isinstance(_lowercase				,     _lowercase   ):
          raise ValueError('Input series is not valid, valid series - [1, 2/3, 2]'   )
     if len(_lowercase   ) == 0:
          raise ValueError('Input list must be a non empty list'   )
     if len(_lowercase   ) == 1 and series[0] != 0:
          return True
     __UpperCamelCase   = []
     __UpperCamelCase   = len(_lowercase   )
     for i in range(0				,     _lowercase   ):
          if series[i] == 0:
               raise ValueError('Input series cannot have 0 as an element'   )
          rec_series.append(1 / series[i]   )
     __UpperCamelCase   = rec_series[1] - rec_series[0]
     for index in range(2				,     _lowercase   ):
          if rec_series[index] - rec_series[index - 1] != common_diff:
               return False
     return True






def 		_A		(		_lowercase   )				->   float:


     """simple docstring"""


     if not isinstance(_lowercase				,     _lowercase   ):
          raise ValueError('Input series is not valid, valid series - [2, 4, 6]'   )
     if len(_lowercase   ) == 0:
          raise ValueError('Input list must be a non empty list'   )
     __UpperCamelCase   = 0
     for val in series:
          answer += 1 / val
     return len(_lowercase   ) / answer


if __name__ == "__main__":
    import doctest

    doctest.testmod()


