






import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaInpaintPipeline,
    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 							snake_case_       (    __UpperCamelCase		,							unittest.TestCase      ):

						"""simple docstring"""



						snake_case__        =      KandinskyVaaInpaintPipeline
						snake_case__        =      ["""image_embeds""", """negative_image_embeds""", """image""", """mask_image"""]
						snake_case__        =      [
						    """image_embeds""",
						    """negative_image_embeds""",
						    """image""",
						    """mask_image""",
						]
						snake_case__        =      [
						    """generator""",
						    """height""",
						    """width""",
						    """latents""",
						    """guidance_scale""",
						    """num_inference_steps""",
						    """return_dict""",
						    """guidance_scale""",
						    """num_images_per_prompt""",
						    """output_type""",
						    """return_dict""",
						]
						snake_case__        =      False



						@property
						def        UpperCAmelCase__					(self:					Any   )    ->     Dict:




											'''simple docstring'''



											return 32



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




											'''simple docstring'''



											return 32



						@property
						def        UpperCAmelCase__					(self:					Union[str, Any]   )    ->     Optional[int]:




											'''simple docstring'''



											return self.time_input_dim



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




											'''simple docstring'''



											return self.time_input_dim * 4



						@property
						def        UpperCAmelCase__					(self:					Tuple   )    ->     str:




											'''simple docstring'''



											return 100



						@property
						def        UpperCAmelCase__					(self:					int   )    ->     int:




											'''simple docstring'''



											torch.manual_seed(0   )

											__a					:						List[str]      =					{
											    "in_channels": 9,
											    # 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,
											}

											__a					:						Union[str, Any]      =					UNetaDConditionModel(**__UpperCAmelCase   )
											return model



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




											'''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:					str   )    ->     Tuple:




											'''simple docstring'''



											torch.manual_seed(0   )
											__a					:						Tuple      =					VQModel(**self.dummy_movq_kwargs   )
											return model



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




											'''simple docstring'''



											__a					:						Tuple      =					self.dummy_unet
											__a					:						str      =					self.dummy_movq

											__a					:						Optional[int]      =					DDIMScheduler(
											    num_train_timesteps=1000 ,					beta_schedule="linear" ,					beta_start=0.0_00_85 ,					beta_end=0.0_12 ,					clip_sample=__UpperCAmelCase ,					set_alpha_to_one=__UpperCAmelCase ,					steps_offset=1 ,					prediction_type="epsilon" ,					thresholding=__UpperCAmelCase ,					)

											__a					:						Union[str, Any]      =					{
											    "unet": unet,
											    "scheduler": scheduler,
											    "movq": movq,
											}

											return components



						def        UpperCAmelCase__					(self:					List[str] ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					Optional[Any]=0   )    ->     Dict:




											'''simple docstring'''



											__a					:						Any      =					floats_tensor((1, self.text_embedder_hidden_size) ,					rng=random.Random(__UpperCAmelCase   )   ).to(__UpperCAmelCase   )
											__a					:						Dict      =					floats_tensor((1, self.text_embedder_hidden_size) ,					rng=random.Random(seed + 1   )   ).to(
											    __UpperCAmelCase   )
											# create init_image
											__a					:						Union[str, Any]      =					floats_tensor((1, 3, 64, 64) ,					rng=random.Random(__UpperCAmelCase   )   ).to(__UpperCAmelCase   )
											__a					:						Any      =					image.cpu().permute(0 ,					2 ,					3 ,					1   )[0]
											__a					:						Optional[int]      =					Image.fromarray(np.uinta(__UpperCAmelCase   )   ).convert("RGB"   ).resize((256, 256)   )
											# create mask
											__a					:						Optional[int]      =					np.ones((64, 64) ,					dtype=np.floataa   )
											__a					:						Any      =					0

											if str(__UpperCAmelCase   ).startswith("mps"   ):
																__a					:						Optional[Any]      =					torch.manual_seed(__UpperCAmelCase   )
											else:
																__a					:						Union[str, Any]      =					torch.Generator(device=__UpperCAmelCase   ).manual_seed(__UpperCAmelCase   )
											__a					:						Union[str, Any]      =					{
											    "image": init_image,
											    "mask_image": mask,
											    "image_embeds": image_embeds,
											    "negative_image_embeds": negative_image_embeds,
											    "generator": generator,
											    "height": 64,
											    "width": 64,
											    "num_inference_steps": 2,
											    "guidance_scale": 4.0,
											    "output_type": "np",
											}
											return inputs



						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     Tuple:




											'''simple docstring'''



											__a					:						str      =					"cpu"

											__a					:						Dict      =					self.get_dummy_components()

											__a					:						str      =					self.pipeline_class(**__UpperCAmelCase   )
											__a					:						Optional[Any]      =					pipe.to(__UpperCAmelCase   )

											pipe.set_progress_bar_config(disable=__UpperCAmelCase   )

											__a					:						Tuple      =					pipe(**self.get_dummy_inputs(__UpperCAmelCase   )   )
											__a					:						List[str]      =					output.images

											__a					:						Dict      =					pipe(
											    **self.get_dummy_inputs(__UpperCAmelCase   ) ,					return_dict=__UpperCAmelCase ,					)[0]

											__a					:						Optional[int]      =					image[0, -3:, -3:, -1]
											__a					:						int      =					image_from_tuple[0, -3:, -3:, -1]

											print(f'image.shape {image.shape}'   )

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

											__a					:						Optional[int]      =					np.array(
											    [0.50_77_59_03, 0.49_52_71_95, 0.48_82_45_43, 0.50_19_22_37, 0.48_64_49_06, 0.49_37_38_14, 0.4_78_05_98, 0.47_23_48_27, 0.48_32_78_48]   )

											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()}'



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




											'''simple docstring'''



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




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

						"""simple docstring"""



						def        UpperCAmelCase__					(self:					Any   )    ->     int:




											'''simple docstring'''



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



						def        UpperCAmelCase__					(self:					Any   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						str      =					load_numpy(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
											    "/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy"   )

											__a					:						List[Any]      =					load_image(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png"   )
											__a					:						int      =					np.ones((768, 768) ,					dtype=np.floataa   )
											__a					:						str      =					0

											__a					:						str      =					"a hat"

											__a					:						Dict      =					KandinskyVaaPriorPipeline.from_pretrained(
											    "kandinsky-community/kandinsky-2-2-prior" ,					torch_dtype=torch.floataa   )
											pipe_prior.to(__UpperCAmelCase   )

											__a					:						str      =					KandinskyVaaInpaintPipeline.from_pretrained(
											    "kandinsky-community/kandinsky-2-2-decoder-inpaint" ,					torch_dtype=torch.floataa   )
											__a					:						Dict      =					pipeline.to(__UpperCAmelCase   )
											pipeline.set_progress_bar_config(disable=__UpperCAmelCase   )

											__a					:						List[str]      =					torch.Generator(device="cpu"   ).manual_seed(0   )
											__a      ,			__a					:						Any      =					pipe_prior(
											    __UpperCAmelCase ,					generator=__UpperCAmelCase ,					num_inference_steps=5 ,					negative_prompt="" ,					).to_tuple()

											__a					:						Optional[Any]      =					pipeline(
											    image=__UpperCAmelCase ,					mask_image=__UpperCAmelCase ,					image_embeds=__UpperCAmelCase ,					negative_image_embeds=__UpperCAmelCase ,					generator=__UpperCAmelCase ,					num_inference_steps=100 ,					height=768 ,					width=768 ,					output_type="np" ,					)

											__a					:						Dict      =					output.images[0]

											assert image.shape == (768, 768, 3)

											assert_mean_pixel_difference(__UpperCAmelCase ,					__UpperCAmelCase   )













import unittest

import numpy as np

from transformers import RobertaConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
			from transformers.models.roberta.modeling_flax_roberta import (
			    FlaxRobertaForCausalLM,
			    FlaxRobertaForMaskedLM,
			    FlaxRobertaForMultipleChoice,
			    FlaxRobertaForQuestionAnswering,
			    FlaxRobertaForSequenceClassification,
			    FlaxRobertaForTokenClassification,
			    FlaxRobertaModel,
			)




class 							snake_case_       (    unittest.TestCase      ):

						"""simple docstring"""



						def __init__(self:					Optional[int] ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					List[str]=13 ,					__UpperCAmelCase:					Any=7 ,					__UpperCAmelCase:					List[str]=True ,					__UpperCAmelCase:					Optional[int]=True ,					__UpperCAmelCase:					Dict=True ,					__UpperCAmelCase:					Optional[Any]=True ,					__UpperCAmelCase:					Optional[int]=99 ,					__UpperCAmelCase:					Optional[Any]=32 ,					__UpperCAmelCase:					int=5 ,					__UpperCAmelCase:					Dict=4 ,					__UpperCAmelCase:					Optional[int]=37 ,					__UpperCAmelCase:					int="gelu" ,					__UpperCAmelCase:					Tuple=0.1 ,					__UpperCAmelCase:					Any=0.1 ,					__UpperCAmelCase:					Union[str, Any]=512 ,					__UpperCAmelCase:					Optional[Any]=16 ,					__UpperCAmelCase:					List[Any]=2 ,					__UpperCAmelCase:					str=0.02 ,					__UpperCAmelCase:					int=4 ,					)    ->     str:




											'''simple docstring'''



											__a					:						Tuple      =					parent
											__a					:						int      =					batch_size
											__a					:						Optional[int]      =					seq_length
											__a					:						List[Any]      =					is_training
											__a					:						Tuple      =					use_attention_mask
											__a					:						Optional[int]      =					use_token_type_ids
											__a					:						Tuple      =					use_labels
											__a					:						str      =					vocab_size
											__a					:						Union[str, Any]      =					hidden_size
											__a					:						List[str]      =					num_hidden_layers
											__a					:						Optional[int]      =					num_attention_heads
											__a					:						Any      =					intermediate_size
											__a					:						Any      =					hidden_act
											__a					:						List[str]      =					hidden_dropout_prob
											__a					:						Dict      =					attention_probs_dropout_prob
											__a					:						Tuple      =					max_position_embeddings
											__a					:						Optional[int]      =					type_vocab_size
											__a					:						Tuple      =					type_sequence_label_size
											__a					:						List[Any]      =					initializer_range
											__a					:						int      =					num_choices



						def        UpperCAmelCase__					(self:					Tuple   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						List[Any]      =					ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size   )

											__a					:						Dict      =					None
											if self.use_attention_mask:
																__a					:						List[Any]      =					random_attention_mask([self.batch_size, self.seq_length]   )

											__a					:						Optional[int]      =					None
											if self.use_token_type_ids:
																__a					:						Dict      =					ids_tensor([self.batch_size, self.seq_length] ,					self.type_vocab_size   )

											__a					:						Dict      =					RobertaConfig(
											    vocab_size=self.vocab_size ,					hidden_size=self.hidden_size ,					num_hidden_layers=self.num_hidden_layers ,					num_attention_heads=self.num_attention_heads ,					intermediate_size=self.intermediate_size ,					hidden_act=self.hidden_act ,					hidden_dropout_prob=self.hidden_dropout_prob ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob ,					max_position_embeddings=self.max_position_embeddings ,					type_vocab_size=self.type_vocab_size ,					is_decoder=__UpperCAmelCase ,					initializer_range=self.initializer_range ,					)

											return config, input_ids, token_type_ids, attention_mask



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




											'''simple docstring'''



											__a					:						Union[str, Any]      =					self.prepare_config_and_inputs()
											__a      ,			__a      ,			__a      ,			__a					:						Dict      =					config_and_inputs
											__a					:						str      =					{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
											return config, inputs_dict



						def        UpperCAmelCase__					(self:					Dict   )    ->     str:




											'''simple docstring'''



											__a					:						Optional[Any]      =					self.prepare_config_and_inputs()
											__a      ,			__a      ,			__a      ,			__a					:						Tuple      =					config_and_inputs

											__a					:						int      =					True
											__a					:						List[str]      =					floats_tensor([self.batch_size, self.seq_length, self.hidden_size]   )
											__a					:						List[Any]      =					ids_tensor([self.batch_size, self.seq_length] ,					vocab_size=2   )

											return (
											    config,
											    input_ids,
											    token_type_ids,
											    encoder_hidden_states,
											    encoder_attention_mask,
											)




@require_flax
class 							snake_case_       (    __UpperCamelCase		,							unittest.TestCase      ):

						"""simple docstring"""



						snake_case__        =      True

						snake_case__        =      (
						    (
						        FlaxRobertaModel,
						        FlaxRobertaForCausalLM,
						        FlaxRobertaForMaskedLM,
						        FlaxRobertaForSequenceClassification,
						        FlaxRobertaForTokenClassification,
						        FlaxRobertaForMultipleChoice,
						        FlaxRobertaForQuestionAnswering,
						    )
						    if is_flax_available()
						    else ()
						)



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




											'''simple docstring'''



											__a					:						Tuple      =					FlaxRobertaModelTester(self   )



						@slow
						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     List[Any]:




											'''simple docstring'''



											for model_class_name in self.all_model_classes:
																__a					:						int      =					model_class_name.from_pretrained("roberta-base" ,					from_pt=__UpperCAmelCase   )
																__a					:						Tuple      =					model(np.ones((1, 1)   )   )
																self.assertIsNotNone(__UpperCAmelCase   )





