




'''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 		SCREAMING_SNAKE_CASE__  (			_UpperCamelCase				,     unittest.TestCase	):
			__SCREAMING_SNAKE_CASE    =			KandinskyVaaImgaImgPipeline
			__SCREAMING_SNAKE_CASE    =			["""image_embeds""", """negative_image_embeds""", """image"""]
			__SCREAMING_SNAKE_CASE    =			[
			    """image_embeds""",
			    """negative_image_embeds""",
			    """image""",
			]
			__SCREAMING_SNAKE_CASE    =			[
			    """generator""",
			    """height""",
			    """width""",
			    """strength""",
			    """guidance_scale""",
			    """num_inference_steps""",
			    """return_dict""",
			    """guidance_scale""",
			    """num_images_per_prompt""",
			    """output_type""",
			    """return_dict""",
			]
			__SCREAMING_SNAKE_CASE    =			False





			@property
			def 							A (      self						:    Any							):



						"""simple docstring"""




						return 32





			@property
			def 							A (      self						:    str							):



						"""simple docstring"""




						return 32





			@property
			def 							A (      self						:    List[Any]							):



						"""simple docstring"""




						return self.time_input_dim





			@property
			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						return self.time_input_dim * 4





			@property
			def 							A (      self						:    Tuple							):



						"""simple docstring"""




						return 100





			@property
			def 							A (      self						:    List[str]							):



						"""simple docstring"""




						torch.manual_seed(0							)

						__snake_case			=		{
						    "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,
						}

						__snake_case			=		UNetaDConditionModel(**a_							)
						return model





			@property
			def 							A (      self						:    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 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						torch.manual_seed(0							)
						__snake_case			=		VQModel(**self.dummy_movq_kwargs							)
						return model





			def 							A (      self						:    List[Any]							):



						"""simple docstring"""




						__snake_case			=		self.dummy_unet
						__snake_case			=		self.dummy_movq

						__snake_case			=		{
						    "num_train_timesteps": 1_000,
						    "beta_schedule": "linear",
						    "beta_start": 0.00085,
						    "beta_end": 0.012,
						    "clip_sample": False,
						    "set_alpha_to_one": False,
						    "steps_offset": 0,
						    "prediction_type": "epsilon",
						    "thresholding": False,
						}

						__snake_case			=		DDIMScheduler(**a_							)

						__snake_case			=		{
						    "unet": unet,
						    "scheduler": scheduler,
						    "movq": movq,
						}

						return components





			def 							A (      self						:    str      ,		a_						:    Any      ,		a_						:    List[Any]=0							):



						"""simple docstring"""




						__snake_case			=		floats_tensor((1, self.text_embedder_hidden_size)      ,		rng=random.Random(a_							)							).to(a_							)
						__snake_case			=		floats_tensor((1, self.text_embedder_hidden_size)      ,		rng=random.Random(seed + 1							)							).to(
						    a_							)
						# create init_image
						__snake_case			=		floats_tensor((1, 3, 64, 64)      ,		rng=random.Random(a_							)							).to(a_							)
						__snake_case			=		image.cpu().permute(0      ,		2      ,		3      ,		1							)[0]
						__snake_case			=		Image.fromarray(np.uinta(a_							)							).convert("RGB"							).resize((256, 256)							)

						if str(a_							).startswith("mps"							):
									__snake_case			=		torch.manual_seed(a_							)
						else:
									__snake_case			=		torch.Generator(device=a_							).manual_seed(a_							)
						__snake_case			=		{
						    "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 							A (      self						:    Any							):



						"""simple docstring"""




						__snake_case			=		"cpu"

						__snake_case			=		self.get_dummy_components()

						__snake_case			=		self.pipeline_class(**a_							)
						__snake_case			=		pipe.to(a_							)

						pipe.set_progress_bar_config(disable=a_							)

						__snake_case			=		pipe(**self.get_dummy_inputs(a_							)							)
						__snake_case			=		output.images

						__snake_case			=		pipe(
						    **self.get_dummy_inputs(a_							)      ,		return_dict=a_      ,		)[0]

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

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

						__snake_case			=		np.array(
						    [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263]							)
						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 		SCREAMING_SNAKE_CASE__  (			unittest.TestCase	):





			def 							A (      self						:    Any							):



						"""simple docstring"""




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






			def 							A (      self						:    Tuple							):



						"""simple docstring"""




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

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

						__snake_case			=		KandinskyVaaPriorPipeline.from_pretrained(
						    "kandinsky-community/kandinsky-2-2-prior"      ,		torch_dtype=torch.floataa							)
						pipe_prior.to(a_							)

						__snake_case			=		KandinskyVaaImgaImgPipeline.from_pretrained(
						    "kandinsky-community/kandinsky-2-2-decoder"      ,		torch_dtype=torch.floataa							)
						__snake_case			=		pipeline.to(a_							)

						pipeline.set_progress_bar_config(disable=a_							)

						__snake_case			=		torch.Generator(device="cpu"							).manual_seed(0							)
						__snake_case		,     __snake_case			=		pipe_prior(
						    a_      ,		generator=a_      ,		num_inference_steps=5      ,		negative_prompt=""      ,		).to_tuple()

						__snake_case			=		pipeline(
						    image=a_      ,		image_embeds=a_      ,		negative_image_embeds=a_      ,		generator=a_      ,		num_inference_steps=100      ,		height=768      ,		width=768      ,		strength=0.2      ,		output_type="np"      ,		)

						__snake_case			=		output.images[0]

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

						assert_mean_pixel_difference(a_      ,		a_							)













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   )





