




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  lowerCAmelCase_    (				self    :						str		):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()



 @property
 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       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(_lowerCAmelCase		)
       return image



 @property
 def  lowerCAmelCase_    (				self    :						Union[str, 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  lowerCAmelCase_    (				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  lowerCAmelCase_    (				self    :						Optional[int]		):
       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(_lowerCAmelCase		)



 @property
 def  lowerCAmelCase_    (				self    :						List[Any]		):
       def extract(*_lowerCAmelCase    :						Optional[int]							,							**_lowerCAmelCase    :						str		):





             class 			lowerCamelCase_				:


              '''simple docstring'''







              def __init__(				self    :						str		):
                    SCREAMING_SNAKE_CASE_      		=     torch.ones([0]		)




              def  lowerCAmelCase_    (				self    :						Union[str, Any]							,							_lowerCAmelCase    :						int		):
                    self.pixel_values.to(_lowerCAmelCase		)
                    return self


             return Out()

       return extract



 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       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=_lowerCAmelCase		)
       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(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     init_image / 2 + 0.5

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

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

       SCREAMING_SNAKE_CASE_      		=     output.images

       SCREAMING_SNAKE_CASE_      		=     torch.Generator(device=_lowerCAmelCase		).manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     alt_pipe(
           [prompt]							,							generator=_lowerCAmelCase							,							guidance_scale=6.0							,							num_inference_steps=2							,							output_type='np'							,							image=_lowerCAmelCase							,							return_dict=_lowerCAmelCase							,							)[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.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  lowerCAmelCase_    (				self    :						Tuple		):
       SCREAMING_SNAKE_CASE_      		=     self.dummy_cond_unet
       SCREAMING_SNAKE_CASE_      		=     PNDMScheduler(skip_prk_steps=_lowerCAmelCase		)
       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(_lowerCAmelCase		)

       # 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=_lowerCAmelCase							,							scheduler=_lowerCAmelCase							,							vae=_lowerCAmelCase							,							text_encoder=_lowerCAmelCase							,							tokenizer=_lowerCAmelCase							,							safety_checker=_lowerCAmelCase							,							feature_extractor=self.dummy_extractor							,							)
       SCREAMING_SNAKE_CASE_      		=     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,							do_normalize=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     alt_pipe.to(_lowerCAmelCase		)
       alt_pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

       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=_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  lowerCAmelCase_    (				self    :						str		):
       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(
           _lowerCAmelCase							,							safety_checker=_lowerCAmelCase							,							)
       pipe.to(_lowerCAmelCase		)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase		)
       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=_lowerCAmelCase							,							image=_lowerCAmelCase							,							strength=0.75							,							guidance_scale=7.5							,							generator=_lowerCAmelCase							,							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.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 			lowerCamelCase_				( unittest.TestCase   ):


 '''simple docstring'''







 def  lowerCAmelCase_    (				self    :						str		):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




 def  lowerCAmelCase_    (				self    :						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(
           _lowerCAmelCase							,							safety_checker=_lowerCAmelCase							,							)
       pipe.to(_lowerCAmelCase		)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase		)
       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=_lowerCAmelCase							,							image=_lowerCAmelCase							,							strength=0.75							,							guidance_scale=7.5							,							generator=_lowerCAmelCase							,							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





from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase__					:  Optional[int]      							=				logging.get_logger(__name__)

lowerCamelCase__					:  Tuple      							=				{
    'microsoft/swinv2-tiny-patch4-window8-256': (
        'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json'
    ),
}





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 lowercase_							       =       "swinv2"

 lowercase_							       =       {
     "num_attention_heads": "num_heads",
     "num_hidden_layers": "num_layers",
 }



 def __init__(				self    :						Dict							,							_lowerCAmelCase    :						Optional[Any]=224							,							_lowerCAmelCase    :						Optional[int]=4							,							_lowerCAmelCase    :						Tuple=3							,							_lowerCAmelCase    :						Tuple=96							,							_lowerCAmelCase    :						Dict=[2, 2, 6, 2]							,							_lowerCAmelCase    :						Optional[Any]=[3, 6, 12, 24]							,							_lowerCAmelCase    :						str=7							,							_lowerCAmelCase    :						List[Any]=4.0							,							_lowerCAmelCase    :						List[str]=True							,							_lowerCAmelCase    :						List[Any]=0.0							,							_lowerCAmelCase    :						List[Any]=0.0							,							_lowerCAmelCase    :						Any=0.1							,							_lowerCAmelCase    :						List[Any]="gelu"							,							_lowerCAmelCase    :						str=False							,							_lowerCAmelCase    :						str=0.02							,							_lowerCAmelCase    :						List[Any]=1E-5							,							_lowerCAmelCase    :						str=32							,							**_lowerCAmelCase    :						List[Any]							,							):
       super().__init__(**_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     image_size
       SCREAMING_SNAKE_CASE_      		=     patch_size
       SCREAMING_SNAKE_CASE_      		=     num_channels
       SCREAMING_SNAKE_CASE_      		=     embed_dim
       SCREAMING_SNAKE_CASE_      		=     depths
       SCREAMING_SNAKE_CASE_      		=     len(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     num_heads
       SCREAMING_SNAKE_CASE_      		=     window_size
       SCREAMING_SNAKE_CASE_      		=     mlp_ratio
       SCREAMING_SNAKE_CASE_      		=     qkv_bias
       SCREAMING_SNAKE_CASE_      		=     hidden_dropout_prob
       SCREAMING_SNAKE_CASE_      		=     attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE_      		=     drop_path_rate
       SCREAMING_SNAKE_CASE_      		=     hidden_act
       SCREAMING_SNAKE_CASE_      		=     use_absolute_embeddings
       SCREAMING_SNAKE_CASE_      		=     layer_norm_eps
       SCREAMING_SNAKE_CASE_      		=     initializer_range
       SCREAMING_SNAKE_CASE_      		=     encoder_stride
       # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
       # this indicates the channel dimension after the last stage of the model
       SCREAMING_SNAKE_CASE_      		=     int(embed_dim * 2 ** (len(_lowerCAmelCase		) - 1)		)
       SCREAMING_SNAKE_CASE_      		=     (0, 0, 0, 0)