
"""simple docstring"""





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
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

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()






class    _UpperCAmelCase(   lowerCamelCase				,					unittest.TestCase     ):
		lowercase__      =				KandinskyVaaImgaImgPipeline
		lowercase__      =				['image_embeds', 'negative_image_embeds', 'image']
		lowercase__      =				[
		    'image_embeds',
		    'negative_image_embeds',
		    'image',
		]
		lowercase__      =				[
		    'generator',
		    'height',
		    'width',
		    'strength',
		    'guidance_scale',
		    'num_inference_steps',
		    'return_dict',
		    'guidance_scale',
		    'num_images_per_prompt',
		    'output_type',
		    'return_dict',
		]
		lowercase__      =				False



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






							'''simple docstring'''
							return 32



		@property
		def 						UpperCAmelCase							( self)	->	Dict:






							'''simple docstring'''
							return 32



		@property
		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							return self.time_input_dim



		@property
		def 						UpperCAmelCase							( self)	->	Any:






							'''simple docstring'''
							return self.time_input_dim * 4



		@property
		def 						UpperCAmelCase							( self)	->	List[str]:






							'''simple docstring'''
							return 1_00



		@property
		def 						UpperCAmelCase							( self)	->	List[str]:






							'''simple docstring'''
							torch.manual_seed(0)

							_UpperCamelCase										=  {
							    '''in_channels''': 4,
							    # Out channels is double in channels because predicts mean and variance
							    '''out_channels''': 8,
							    '''addition_embed_type''': '''image''',
							    '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
							    '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
							    '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
							    '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
							    '''layers_per_block''': 1,
							    '''encoder_hid_dim''': self.text_embedder_hidden_size,
							    '''encoder_hid_dim_type''': '''image_proj''',
							    '''cross_attention_dim''': self.cross_attention_dim,
							    '''attention_head_dim''': 4,
							    '''resnet_time_scale_shift''': '''scale_shift''',
							    '''class_embed_type''': None,
							}

							_UpperCamelCase										=  UNetaDConditionModel(**__a)
							return model



		@property
		def 						UpperCAmelCase							( self)	->	Optional[int]:






							'''simple docstring'''
							return {
							    "block_out_channels": [32, 64],
							    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
							    "in_channels": 3,
							    "latent_channels": 4,
							    "layers_per_block": 1,
							    "norm_num_groups": 8,
							    "norm_type": "spatial",
							    "num_vq_embeddings": 12,
							    "out_channels": 3,
							    "up_block_types": [
							        "AttnUpDecoderBlock2D",
							        "UpDecoderBlock2D",
							    ],
							    "vq_embed_dim": 4,
							}



		@property
		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							torch.manual_seed(0)
							_UpperCamelCase										=  VQModel(**self.dummy_movq_kwargs)
							return model



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






							'''simple docstring'''
							_UpperCamelCase										=  self.dummy_unet
							_UpperCamelCase										=  self.dummy_movq

							_UpperCamelCase										=  {
							    '''num_train_timesteps''': 10_00,
							    '''beta_schedule''': '''linear''',
							    '''beta_start''': 0.0_0085,
							    '''beta_end''': 0.012,
							    '''clip_sample''': False,
							    '''set_alpha_to_one''': False,
							    '''steps_offset''': 0,
							    '''prediction_type''': '''epsilon''',
							    '''thresholding''': False,
							}

							_UpperCamelCase										=  DDIMScheduler(**__a)

							_UpperCamelCase										=  {
							    '''unet''': unet,
							    '''scheduler''': scheduler,
							    '''movq''': movq,
							}

							return components



		def 						UpperCAmelCase							( self    ,		__a    ,		__a=0)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  floats_tensor((1, self.text_embedder_hidden_size)    ,		rng=random.Random(__a)).to(__a)
							_UpperCamelCase										=  floats_tensor((1, self.text_embedder_hidden_size)    ,		rng=random.Random(seed + 1)).to(
							    __a)
							# create init_image
							_UpperCamelCase										=  floats_tensor((1, 3, 64, 64)    ,		rng=random.Random(__a)).to(__a)
							_UpperCamelCase										=  image.cpu().permute(0    ,		2    ,		3    ,		1)[0]
							_UpperCamelCase										=  Image.fromarray(np.uinta(__a)).convert('''RGB''').resize((2_56, 2_56))

							if str(__a).startswith('''mps'''):
												_UpperCamelCase										=  torch.manual_seed(__a)
							else:
												_UpperCamelCase										=  torch.Generator(device=__a).manual_seed(__a)
							_UpperCamelCase										=  {
							    '''image''': init_image,
							    '''image_embeds''': image_embeds,
							    '''negative_image_embeds''': negative_image_embeds,
							    '''generator''': generator,
							    '''height''': 64,
							    '''width''': 64,
							    '''num_inference_steps''': 10,
							    '''guidance_scale''': 7.0,
							    '''strength''': 0.2,
							    '''output_type''': '''np''',
							}
							return inputs




		def 						UpperCAmelCase							( self)	->	Optional[int]:






							'''simple docstring'''
							_UpperCamelCase										=  '''cpu'''

							_UpperCamelCase										=  self.get_dummy_components()

							_UpperCamelCase										=  self.pipeline_class(**__a)
							_UpperCamelCase										=  pipe.to(__a)

							pipe.set_progress_bar_config(disable=__a)

							_UpperCamelCase										=  pipe(**self.get_dummy_inputs(__a))
							_UpperCamelCase										=  output.images

							_UpperCamelCase										=  pipe(
							    **self.get_dummy_inputs(__a)    ,		return_dict=__a    ,		)[0]

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

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

							_UpperCamelCase										=  np.array(
							    [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263])
							assert (
							    np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
							), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
							assert (
							    np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
							), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''






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



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






							'''simple docstring'''
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()




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






							'''simple docstring'''
							_UpperCamelCase										=  load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/kandinskyv22/kandinskyv22_img2img_frog.npy''')

							_UpperCamelCase										=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''')
							_UpperCamelCase										=  '''A red cartoon frog, 4k'''

							_UpperCamelCase										=  KandinskyVaaPriorPipeline.from_pretrained(
							    '''kandinsky-community/kandinsky-2-2-prior'''    ,		torch_dtype=torch.floataa)
							pipe_prior.to(__a)

							_UpperCamelCase										=  KandinskyVaaImgaImgPipeline.from_pretrained(
							    '''kandinsky-community/kandinsky-2-2-decoder'''    ,		torch_dtype=torch.floataa)
							_UpperCamelCase										=  pipeline.to(__a)

							pipeline.set_progress_bar_config(disable=__a)

							_UpperCamelCase										=  torch.Generator(device='''cpu''').manual_seed(0)
							_UpperCamelCase			,  _UpperCamelCase										=  pipe_prior(
							    __a    ,		generator=__a    ,		num_inference_steps=5    ,		negative_prompt=''''''    ,		).to_tuple()

							_UpperCamelCase										=  pipeline(
							    image=__a    ,		image_embeds=__a    ,		negative_image_embeds=__a    ,		generator=__a    ,		num_inference_steps=1_00    ,		height=7_68    ,		width=7_68    ,		strength=0.2    ,		output_type='''np'''    ,		)

							_UpperCamelCase										=  output.images[0]

							assert image.shape == (7_68, 7_68, 3)

							assert_mean_pixel_difference(__a    ,		__a)








"""simple docstring"""





from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_a														=		logging.get_logger(__name__)

_a														=		{
    """facebook/xlm-roberta-xl""": """https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json""",
    """facebook/xlm-roberta-xxl""": """https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json""",
    # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl
}






class    _UpperCAmelCase(   lowerCamelCase     ):
		lowercase__      =				'xlm-roberta-xl'



		def __init__( self    ,		__a=25_08_80    ,		__a=25_60    ,		__a=36    ,		__a=32    ,		__a=1_02_40    ,		__a="gelu"    ,		__a=0.1    ,		__a=0.1    ,		__a=5_14    ,		__a=1    ,		__a=0.02    ,		__a=1e-05    ,		__a=1    ,		__a=0    ,		__a=2    ,		__a="absolute"    ,		__a=True    ,		__a=None    ,		**__a    ,		)	->	Tuple:






							'''simple docstring'''
							super().__init__(pad_token_id=__a    ,		bos_token_id=__a    ,		eos_token_id=__a    ,		**__a)
							_UpperCamelCase										=  vocab_size
							_UpperCamelCase										=  hidden_size
							_UpperCamelCase										=  num_hidden_layers
							_UpperCamelCase										=  num_attention_heads
							_UpperCamelCase										=  hidden_act
							_UpperCamelCase										=  intermediate_size
							_UpperCamelCase										=  hidden_dropout_prob
							_UpperCamelCase										=  attention_probs_dropout_prob
							_UpperCamelCase										=  max_position_embeddings
							_UpperCamelCase										=  type_vocab_size
							_UpperCamelCase										=  initializer_range
							_UpperCamelCase										=  layer_norm_eps
							_UpperCamelCase										=  position_embedding_type
							_UpperCamelCase										=  use_cache
							_UpperCamelCase										=  classifier_dropout






class    _UpperCAmelCase(   lowerCamelCase     ):



		@property
		def 						UpperCAmelCase							( self)	->	Mapping[str, Mapping[int, str]]:






							'''simple docstring'''
							if self.task == "multiple-choice":
												_UpperCamelCase										=  {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
							else:
												_UpperCamelCase										=  {0: '''batch''', 1: '''sequence'''}
							return OrderedDict(
							    [
							        ('''input_ids''', dynamic_axis),
							        ('''attention_mask''', dynamic_axis),
							    ])






