



import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
       from transformers import (
           FlaxBertModel,
           FlaxCLIPVisionModel,
           FlaxVisionTextDualEncoderModel,
           FlaxViTModel,
           VisionTextDualEncoderConfig,
           VisionTextDualEncoderProcessor,
       )
       from transformers.modeling_flax_pytorch_utils import (
           convert_pytorch_state_dict_to_flax,
           load_flax_weights_in_pytorch_model,
       )


if is_torch_available():
       import torch

       from transformers import VisionTextDualEncoderModel

if is_vision_available():
       from PIL import Image




def 		SCREAMING_SNAKE_CASE     (     snake_case__      )   ->	List[Any]:
    if isinstance(__lowerCAmelCase				,   collections.abc.Iterable      ):
        return x
    return (x, x)



@require_flax
class        _SCREAMING_SNAKE_CASE		:





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase):
       '''simple docstring'''







       pass





   def 	A__      (self):
       '''simple docstring'''







       pass





   def 	A__      (self):
       '''simple docstring'''







       pass





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =np.abs((a - b)).max()
       self.assertLessEqual(lowerCamelCase__    ,  lowerCamelCase__    ,  f"""Difference between torch and flax is {diff} (>= {tol}).""")





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase=None    ,  **UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__    ,  lowerCamelCase__)

       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel(lowerCamelCase__)

       __UpperCAmelCase			 =model(input_ids=lowerCamelCase__    ,  pixel_values=lowerCamelCase__    ,  attention_mask=lowerCamelCase__)

       self.assertEqual(output['''text_embeds'''].shape    ,  (input_ids.shape[0], config.projection_dim))
       self.assertEqual(output['''image_embeds'''].shape    ,  (pixel_values.shape[0], config.projection_dim))





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase=None    ,  **UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =self.get_vision_text_model(lowerCamelCase__    ,  lowerCamelCase__)
       __UpperCAmelCase			 ={"""vision_model""": vision_model, """text_model""": text_model}
       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__)

       __UpperCAmelCase			 =model(input_ids=lowerCamelCase__    ,  pixel_values=lowerCamelCase__    ,  attention_mask=lowerCamelCase__)

       self.assertEqual(output['''text_embeds'''].shape    ,  (input_ids.shape[0], model.config.projection_dim))
       self.assertEqual(output['''image_embeds'''].shape    ,  (pixel_values.shape[0], model.config.projection_dim))





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase=None    ,  **UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =self.get_vision_text_model(lowerCamelCase__    ,  lowerCamelCase__)
       __UpperCAmelCase			 ={"""vision_model""": vision_model, """text_model""": text_model}
       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__)

       __UpperCAmelCase			 =model(input_ids=lowerCamelCase__    ,  pixel_values=lowerCamelCase__    ,  attention_mask=lowerCamelCase__)
       __UpperCAmelCase			 =output[0]

       with tempfile.TemporaryDirectory() as tmpdirname:
           model.save_pretrained(lowerCamelCase__)
           __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__)

           __UpperCAmelCase			 =model(input_ids=lowerCamelCase__    ,  pixel_values=lowerCamelCase__    ,  attention_mask=lowerCamelCase__)
           __UpperCAmelCase			 =after_output[0]
           __UpperCAmelCase			 =np.amax(np.abs(out_a - out_a))
           self.assertLessEqual(lowerCamelCase__    ,  1e-3)





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase=None    ,  **UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =self.get_vision_text_model(lowerCamelCase__    ,  lowerCamelCase__)
       __UpperCAmelCase			 ={"""vision_model""": vision_model, """text_model""": text_model}
       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__)

       __UpperCAmelCase			 =model(
           input_ids=lowerCamelCase__    ,  pixel_values=lowerCamelCase__    ,  attention_mask=lowerCamelCase__    ,  output_attentions=lowerCamelCase__)

       __UpperCAmelCase			 =output.vision_model_output.attentions
       self.assertEqual(len(lowerCamelCase__)    ,  vision_config.num_hidden_layers)

       # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
       __UpperCAmelCase			 =to_atuple(vision_model.config.image_size)
       __UpperCAmelCase			 =to_atuple(vision_model.config.patch_size)
       __UpperCAmelCase			 =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
       __UpperCAmelCase			 =num_patches + 1
       self.assertEqual(vision_attentions[0].shape[-3:]    ,  (vision_config.num_attention_heads, seq_len, seq_len))

       __UpperCAmelCase			 =output.text_model_output.attentions
       self.assertEqual(len(lowerCamelCase__)    ,  text_config.num_hidden_layers)

       self.assertEqual(
           text_attentions[0].shape[-3:]    ,  (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])    ,  )





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase):
       '''simple docstring'''







       pt_model.to(lowerCamelCase__)
       pt_model.eval()

       # prepare inputs
       __UpperCAmelCase			 =inputs_dict
       __UpperCAmelCase			 ={k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()}

       with torch.no_grad():
           __UpperCAmelCase			 =pt_model(**lowerCamelCase__).to_tuple()

       __UpperCAmelCase			 =fx_model(**lowerCamelCase__).to_tuple()
       self.assertEqual(len(lowerCamelCase__)    ,  len(lowerCamelCase__)    ,  '''Output lengths differ between Flax and PyTorch''')
       for fx_output, pt_output in zip(fx_outputs[:4]    ,  pt_outputs[:4]):
           self.assert_almost_equals(lowerCamelCase__    ,  pt_output.numpy()    ,  4e-2)

       # PT -> Flax
       with tempfile.TemporaryDirectory() as tmpdirname:
           pt_model.save_pretrained(lowerCamelCase__)
           __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__    ,  from_pt=lowerCamelCase__)

       __UpperCAmelCase			 =fx_model_loaded(**lowerCamelCase__).to_tuple()
       self.assertEqual(len(lowerCamelCase__)    ,  len(lowerCamelCase__)    ,  '''Output lengths differ between Flax and PyTorch''')
       for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]    ,  pt_outputs[:4]):
           self.assert_almost_equals(lowerCamelCase__    ,  pt_output.numpy()    ,  4e-2)

       # Flax -> PT
       with tempfile.TemporaryDirectory() as tmpdirname:
           fx_model.save_pretrained(lowerCamelCase__)
           __UpperCAmelCase			 =VisionTextDualEncoderModel.from_pretrained(lowerCamelCase__    ,  from_flax=lowerCamelCase__)

       pt_model_loaded.to(lowerCamelCase__)
       pt_model_loaded.eval()

       with torch.no_grad():
           __UpperCAmelCase			 =pt_model_loaded(**lowerCamelCase__).to_tuple()

       self.assertEqual(len(lowerCamelCase__)    ,  len(lowerCamelCase__)    ,  '''Output lengths differ between Flax and PyTorch''')
       for fx_output, pt_output_loaded in zip(fx_outputs[:4]    ,  pt_outputs_loaded[:4]):
           self.assert_almost_equals(lowerCamelCase__    ,  pt_output_loaded.numpy()    ,  4e-2)





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__    ,  lowerCamelCase__)

       __UpperCAmelCase			 =VisionTextDualEncoderModel(lowerCamelCase__)
       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel(lowerCamelCase__)

       __UpperCAmelCase			 =convert_pytorch_state_dict_to_flax(pt_model.state_dict()    ,  lowerCamelCase__)
       __UpperCAmelCase			 =fx_state

       self.check_pt_flax_equivalence(lowerCamelCase__    ,  lowerCamelCase__    ,  lowerCamelCase__)





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__    ,  lowerCamelCase__)

       __UpperCAmelCase			 =VisionTextDualEncoderModel(lowerCamelCase__)
       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel(lowerCamelCase__)

       __UpperCAmelCase			 =load_flax_weights_in_pytorch_model(lowerCamelCase__    ,  fx_model.params)

       self.check_pt_flax_equivalence(lowerCamelCase__    ,  lowerCamelCase__    ,  lowerCamelCase__)





   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =self.prepare_config_and_inputs()
       self.check_model_from_pretrained_configs(**lowerCamelCase__)





   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =self.prepare_config_and_inputs()
       self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase__)





   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =self.prepare_config_and_inputs()
       self.check_save_load(**lowerCamelCase__)





   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =self.prepare_config_and_inputs()
       self.check_vision_text_output_attention(**lowerCamelCase__)





   @is_pt_flax_cross_test
   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =self.prepare_config_and_inputs()
       __UpperCAmelCase			 =config_inputs_dict.pop('''vision_config''')
       __UpperCAmelCase			 =config_inputs_dict.pop('''text_config''')

       __UpperCAmelCase			 =config_inputs_dict

       self.check_equivalence_pt_to_flax(lowerCamelCase__    ,  lowerCamelCase__    ,  lowerCamelCase__)
       self.check_equivalence_flax_to_pt(lowerCamelCase__    ,  lowerCamelCase__    ,  lowerCamelCase__)






   @slow
   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =self.get_pretrained_model_and_inputs()

       __UpperCAmelCase			 =model_a(**lowerCamelCase__)
       __UpperCAmelCase			 =outputs[0]

       with tempfile.TemporaryDirectory() as tmp_dirname:
           model_a.save_pretrained(lowerCamelCase__)
           __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__)

           __UpperCAmelCase			 =model_a(**lowerCamelCase__)
           __UpperCAmelCase			 =after_outputs[0]
           __UpperCAmelCase			 =np.amax(np.abs(out_a - out_a))
           self.assertLessEqual(lowerCamelCase__    ,  1e-5)







@require_flax
class        _SCREAMING_SNAKE_CASE		(       UpperCAmelCase_			,			unittest.TestCase ):





   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
           '''hf-internal-testing/tiny-random-vit'''    ,  '''hf-internal-testing/tiny-bert'''    ,  vision_from_pt=lowerCamelCase__    ,  text_from_pt=lowerCamelCase__    ,  )
       __UpperCAmelCase			 =1_3
       __UpperCAmelCase			 =floats_tensor(
           [
               batch_size,
               model.config.vision_config.num_channels,
               model.config.vision_config.image_size,
               model.config.vision_config.image_size,
           ])
       __UpperCAmelCase			 =ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size)
       __UpperCAmelCase			 =random_attention_mask([batch_size, 4])
       __UpperCAmelCase			 ={"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

       return model, inputs





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =FlaxViTModel(lowerCamelCase__)
       __UpperCAmelCase			 =FlaxBertModel(lowerCamelCase__)
       return vision_model, text_model






   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =FlaxViTModelTester(self)
       __UpperCAmelCase			 =FlaxBertModelTester(self)
       __UpperCAmelCase			 =vit_model_tester.prepare_config_and_inputs()
       __UpperCAmelCase			 =bert_model_tester.prepare_config_and_inputs()

       __UpperCAmelCase			 =vision_config_and_inputs

       __UpperCAmelCase			 =text_config_and_inputs

       # make sure that cross attention layers are added
       return {
           "text_config": text_config,
           "vision_config": vision_config,
           "pixel_values": pixel_values,
           "attention_mask": attention_mask,
           "input_ids": input_ids,
           "token_type_ids": token_type_ids,
       }







@require_torch
class        _SCREAMING_SNAKE_CASE		(       UpperCAmelCase_			,			unittest.TestCase ):





   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
           '''hf-internal-testing/tiny-random-clip'''    ,  '''hf-internal-testing/tiny-bert'''    ,  vision_from_pt=lowerCamelCase__    ,  text_from_pt=lowerCamelCase__    ,  )
       __UpperCAmelCase			 =1_3
       __UpperCAmelCase			 =floats_tensor(
           [
               batch_size,
               model.config.vision_config.num_channels,
               model.config.vision_config.image_size,
               model.config.vision_config.image_size,
           ])
       __UpperCAmelCase			 =ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size)
       __UpperCAmelCase			 =random_attention_mask([batch_size, 4])
       __UpperCAmelCase			 ={"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

       return model, inputs





   def 	A__      (self    ,  UpperCAmelCase    ,  UpperCAmelCase):
       '''simple docstring'''







       __UpperCAmelCase			 =FlaxCLIPVisionModel(lowerCamelCase__)
       __UpperCAmelCase			 =FlaxBertModel(lowerCamelCase__)
       return vision_model, text_model






   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =FlaxCLIPVisionModelTester(self)
       __UpperCAmelCase			 =FlaxBertModelTester(self)
       __UpperCAmelCase			 =clip_model_tester.prepare_config_and_inputs()
       __UpperCAmelCase			 =bert_model_tester.prepare_config_and_inputs()

       __UpperCAmelCase			 =vision_config_and_inputs

       __UpperCAmelCase			 =text_config_and_inputs

       # make sure that cross attention layers are added
       return {
           "text_config": text_config,
           "vision_config": vision_config,
           "pixel_values": pixel_values,
           "attention_mask": attention_mask,
           "input_ids": input_ids,
           "token_type_ids": token_type_ids,
       }







@require_flax
@require_vision
class        _SCREAMING_SNAKE_CASE		(       unittest.TestCase ):





   @slow
   def 	A__      (self):
       '''simple docstring'''







       __UpperCAmelCase			 =FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian'''    ,  logit_scale_init_value=1.0)
       __UpperCAmelCase			 =VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''')

       __UpperCAmelCase			 =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
       __UpperCAmelCase			 =processor(
           text=['''una foto di un gatto''', '''una foto di un cane''']    ,  images=lowerCamelCase__    ,  padding=lowerCamelCase__    ,  return_tensors='''np''')

       __UpperCAmelCase			 =model(**lowerCamelCase__)

       # verify the logits
       self.assertEqual(outputs.logits_per_image.shape    ,  (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]))
       self.assertEqual(
           outputs.logits_per_text.shape    ,  (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])    ,  )

       __UpperCAmelCase			 =np.array([[1.228_4727, 0.310_4122]])

       self.assertTrue(np.allclose(outputs.logits_per_image    ,  lowerCamelCase__    ,  atol=1e-3))











import gc
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.utils import floats_tensor, 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 		_A						( UpperCAmelCase_	,				unittest.TestCase ):
  lowercase_						:			int						=					KandinskyVaaPipeline
  lowercase_						:			Union[str, Any]						=					[
      '''image_embeds''',
      '''negative_image_embeds''',
  ]
  lowercase_						:			int						=					['''image_embeds''', '''negative_image_embeds''']
  lowercase_						:			str						=					[
      '''generator''',
      '''height''',
      '''width''',
      '''latents''',
      '''guidance_scale''',
      '''num_inference_steps''',
      '''return_dict''',
      '''guidance_scale''',
      '''num_images_per_prompt''',
      '''output_type''',
      '''return_dict''',
  ]
  lowercase_						:			str						=					False

  @property
  def    a					(    self						:	int			):
     """simple docstring"""

     return 32

  @property
  def    a					(    self						:	str			):
     """simple docstring"""

     return 32

  @property
  def    a					(    self						:	Optional[int]			):
     """simple docstring"""

     return self.time_input_dim

  @property
  def    a					(    self						:	Optional[int]			):
     """simple docstring"""

     return self.time_input_dim * 4

  @property
  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     return 1_00

  @property
  def    a					(    self						:	str			):
     """simple docstring"""

     torch.manual_seed(0			)

     __UpperCamelCase	:			int					=					{
         """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	:			Any					=					UNetaDConditionModel(**lowerCamelCase__			)
     return model

  @property
  def    a					(    self						:	Union[str, 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						:	int			):
     """simple docstring"""

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

  def    a					(    self						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	:			str					=					self.dummy_unet
     __UpperCamelCase	:			Optional[int]					=					self.dummy_movq

     __UpperCamelCase	:			List[str]					=					DDIMScheduler(
         num_train_timesteps=10_00   ,				beta_schedule="""linear"""   ,				beta_start=0.0_0085   ,				beta_end=0.012   ,				clip_sample=lowerCamelCase__   ,				set_alpha_to_one=lowerCamelCase__   ,				steps_offset=1   ,				prediction_type="""epsilon"""   ,				thresholding=lowerCamelCase__   ,				)

     __UpperCamelCase	:			str					=					{
         """unet""": unet,
         """scheduler""": scheduler,
         """movq""": movq,
     }
     return components

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	Optional[Any]   ,				lowerCamelCase__						:	Any=0			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					floats_tensor((1, self.text_embedder_hidden_size)   ,				rng=random.Random(lowerCamelCase__			)			).to(lowerCamelCase__			)
     __UpperCamelCase	:			Optional[int]					=					floats_tensor((1, self.text_embedder_hidden_size)   ,				rng=random.Random(seed + 1			)			).to(
         lowerCamelCase__			)
     if str(lowerCamelCase__			).startswith("""mps"""			):
        __UpperCamelCase	:			Optional[int]					=					torch.manual_seed(lowerCamelCase__			)
     else:
        __UpperCamelCase	:			int					=					torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
     __UpperCamelCase	:			Dict					=					{
         """image_embeds""": image_embeds,
         """negative_image_embeds""": negative_image_embeds,
         """generator""": generator,
         """height""": 64,
         """width""": 64,
         """guidance_scale""": 4.0,
         """num_inference_steps""": 2,
         """output_type""": """np""",
     }
     return inputs

  def    a					(    self						:	Dict			):
     """simple docstring"""

     __UpperCamelCase	:			Dict					=					"""cpu"""

     __UpperCamelCase	:			Dict					=					self.get_dummy_components()

     __UpperCamelCase	:			Union[str, Any]					=					self.pipeline_class(**lowerCamelCase__			)
     __UpperCamelCase	:			int					=					pipe.to(lowerCamelCase__			)

     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     __UpperCamelCase	:			List[Any]					=					pipe(**self.get_dummy_inputs(lowerCamelCase__			)			)
     __UpperCamelCase	:			List[Any]					=					output.images

     __UpperCamelCase	:			int					=					pipe(
         **self.get_dummy_inputs(lowerCamelCase__			)   ,				return_dict=lowerCamelCase__   ,				)[0]

     __UpperCamelCase	:			List[str]					=					image[0, -3:, -3:, -1]
     __UpperCamelCase	:			Tuple					=					image_from_tuple[0, -3:, -3:, -1]

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

     __UpperCamelCase	:			int					=					np.array(
         [0.623_7976, 1.0, 0.3644_1332, 1.0, 0.7063_9634, 0.2987_7186, 0.8565_2125, 0.521_6843, 0.5445_4046]			)

     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 		_A						( unittest.TestCase ):

  def    a					(    self						:	Optional[int]			):
     """simple docstring"""

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

  def    a					(    self						:	List[Any]			):
     """simple docstring"""

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

     __UpperCamelCase	:			List[str]					=					KandinskyVaaPriorPipeline.from_pretrained(
         """kandinsky-community/kandinsky-2-2-prior"""   ,				torch_dtype=torch.floataa			)
     pipe_prior.to(lowerCamelCase__			)

     __UpperCamelCase	:			int					=					KandinskyVaaPipeline.from_pretrained(
         """kandinsky-community/kandinsky-2-2-decoder"""   ,				torch_dtype=torch.floataa			)
     __UpperCamelCase	:			Optional[int]					=					pipeline.to(lowerCamelCase__			)
     pipeline.set_progress_bar_config(disable=lowerCamelCase__			)

     __UpperCamelCase	:			Optional[Any]					=					"""red cat, 4k photo"""

     __UpperCamelCase	:			Tuple					=					torch.Generator(device="""cuda"""			).manual_seed(0			)
     __UpperCamelCase	,     __UpperCamelCase	:			Union[str, Any]					=					pipe_prior(
         lowerCamelCase__   ,				generator=lowerCamelCase__   ,				num_inference_steps=5   ,				negative_prompt=""""""   ,				).to_tuple()

     __UpperCamelCase	:			Any					=					torch.Generator(device="""cuda"""			).manual_seed(0			)
     __UpperCamelCase	:			Union[str, Any]					=					pipeline(
         image_embeds=lowerCamelCase__   ,				negative_image_embeds=lowerCamelCase__   ,				generator=lowerCamelCase__   ,				num_inference_steps=1_00   ,				output_type="""np"""   ,				)

     __UpperCamelCase	:			Any					=					output.images[0]

     assert image.shape == (5_12, 5_12, 3)

     assert_mean_pixel_difference(lowerCamelCase__   ,				lowerCamelCase__			)



