

'''simple docstring'''




import numpy as np

from transformers import BatchFeature
from transformers.testing_utils import require_tf, require_torch

from .test_feature_extraction_common import FeatureExtractionSavingTestMixin






class     _SCREAMING_SNAKE_CASE       (       __a      ):
 # to overwrite at feature extractactor specific tests
 __SCREAMING_SNAKE_CASE	:Dict     			=	None
 __SCREAMING_SNAKE_CASE	:List[str]     			=	None



 @property
 def 					snake_case__    (       self						:       Dict     ):
      return self.feat_extract_tester.prepare_feat_extract_dict()



 def 					snake_case__    (       self						:       str     ):
      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      self.assertTrue(hasattr(a__					, '''feature_size'''     )     )
      self.assertTrue(hasattr(a__					, '''sampling_rate'''     )     )
      self.assertTrue(hasattr(a__					, '''padding_value'''     )     )



 def 					snake_case__    (       self						:       List[str]     ):
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common()
      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}     )

      self.assertTrue(all(len(a__     ) == len(a__     ) for x, y in zip(a__					, processed_features[input_name]     )     )     )

      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common(equal_length=a__     )
      __magic_name__		  =							BatchFeature({input_name: speech_inputs}					, tensor_type='''np'''     )

      __magic_name__		  =							processed_features[input_name]

      if len(batch_features_input.shape     ) < 3:
           __magic_name__		  =							batch_features_input[:, :, None]

      self.assertTrue(
          batch_features_input.shape
          == (self.feat_extract_tester.batch_size, len(speech_inputs[0]     ), self.feat_extract_tester.feature_size)     )



 @require_torch
 def 					snake_case__    (       self						:       Optional[Any]     ):
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common(equal_length=a__     )
      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}					, tensor_type='''pt'''     )

      __magic_name__		  =							processed_features[input_name]

      if len(batch_features_input.shape     ) < 3:
           __magic_name__		  =							batch_features_input[:, :, None]

      self.assertTrue(
          batch_features_input.shape
          == (self.feat_extract_tester.batch_size, len(speech_inputs[0]     ), self.feat_extract_tester.feature_size)     )



 @require_tf
 def 					snake_case__    (       self						:       str     ):
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common(equal_length=a__     )
      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}					, tensor_type='''tf'''     )

      __magic_name__		  =							processed_features[input_name]

      if len(batch_features_input.shape     ) < 3:
           __magic_name__		  =							batch_features_input[:, :, None]

      self.assertTrue(
          batch_features_input.shape
          == (self.feat_extract_tester.batch_size, len(speech_inputs[0]     ), self.feat_extract_tester.feature_size)     )



 def 					snake_case__    (       self						:       Union[str, Any]					, a__						:       List[str]=False     ):
      def _inputs_have_equal_length(a__						:       Tuple     ):
           __magic_name__		  =							len(input[0]     )
           for input_slice in input[1:]:
                if len(a__     ) != length:
                     return False
           return True

      def _inputs_are_equal(a__						:       Optional[int]					, a__						:       List[str]     ):
           if len(a__     ) != len(a__     ):
                return False

           for input_slice_a, input_slice_a in zip(a__					, a__     ):
                if not np.allclose(np.asarray(a__     )					, np.asarray(a__     )					, atol=1E-3     ):
                     return False
           return True

      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common(numpify=a__     )
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}     )

      __magic_name__		  =							self.feat_extract_tester.seq_length_diff
      __magic_name__		  =							self.feat_extract_tester.max_seq_length + pad_diff
      __magic_name__		  =							self.feat_extract_tester.min_seq_length
      __magic_name__		  =							self.feat_extract_tester.batch_size
      __magic_name__		  =							self.feat_extract_tester.feature_size

      # test padding for List[int] + numpy
      __magic_name__		  =							feat_extract.pad(a__					, padding=a__     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(a__					, padding='''max_length'''					, max_length=len(speech_inputs[-1]     )     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''					, return_tensors='''np'''     )
      __magic_name__		  =							input_a[input_name]

      # max_length parameter has to be provided when setting `padding="max_length"`
      with self.assertRaises(a__     ):
           feat_extract.pad(a__					, padding='''max_length'''     )[input_name]

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=a__					, return_tensors='''np'''     )
      __magic_name__		  =							input_a[input_name]

      self.assertFalse(_inputs_have_equal_length(a__     )     )
      self.assertTrue(_inputs_have_equal_length(a__     )     )
      self.assertTrue(_inputs_have_equal_length(a__     )     )
      self.assertTrue(_inputs_are_equal(a__					, a__     )     )
      self.assertTrue(len(input_a[0]     ) == pad_min_length     )
      self.assertTrue(len(input_a[1]     ) == pad_min_length + pad_diff     )
      self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0]     ))     )
      self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length)     )

      if feature_size > 1:
           self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size     )

      # test padding for `pad_to_multiple_of` for List[int] + numpy
      __magic_name__		  =							feat_extract.pad(a__					, pad_to_multiple_of=10     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''					, pad_to_multiple_of=10     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, pad_to_multiple_of=10					, max_length=a__     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, pad_to_multiple_of=10					, max_length=a__					, return_tensors='''np'''					, )
      __magic_name__		  =							input_a[input_name]

      self.assertTrue(all(len(a__     ) % 10 == 0 for x in input_a     )     )
      self.assertTrue(_inputs_are_equal(a__					, a__     )     )

      __magic_name__		  =							pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10
      self.assertTrue(all(len(a__     ) == expected_mult_pad_length for x in input_a     )     )
      self.assertEqual(input_a.shape[:2]					, (batch_size, expected_mult_pad_length)     )

      if feature_size > 1:
           self.assertTrue(input_a.shape[2] == feature_size     )

      # Check padding value is correct
      __magic_name__		  =							(np.ones(self.feat_extract_tester.feature_size     ) * feat_extract.padding_value).sum()
      self.assertTrue(
          abs(np.asarray(input_a[0]     )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)     )
          < 1E-3     )
      self.assertTrue(
          abs(
              np.asarray(input_a[1]     )[pad_min_length + pad_diff :].sum()
              - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff)     )
          < 1E-3     )
      self.assertTrue(
          abs(
              np.asarray(input_a[2]     )[pad_min_length + 2 * pad_diff :].sum()
              - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff)     )
          < 1E-3     )
      self.assertTrue(
          abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)     ) < 1E-3     )
      self.assertTrue(
          abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)     )
          < 1E-3     )



 def 					snake_case__    (       self						:       int					, a__						:       Tuple=False     ):
      def _inputs_have_equal_length(a__						:       Tuple     ):
           __magic_name__		  =							len(input[0]     )
           for input_slice in input[1:]:
                if len(a__     ) != length:
                     return False
           return True

      def _inputs_are_equal(a__						:       Union[str, Any]					, a__						:       int     ):
           if len(a__     ) != len(a__     ):
                return False

           for input_slice_a, input_slice_a in zip(a__					, a__     ):
                if not np.allclose(np.asarray(a__     )					, np.asarray(a__     )					, atol=1E-3     ):
                     return False
           return True

      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common(numpify=a__     )
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}     )

      # truncate to smallest
      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[0]     )					, truncation=a__     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(a__					, padding='''max_length'''					, max_length=len(speech_inputs[0]     )     )
      __magic_name__		  =							input_a[input_name]

      self.assertTrue(_inputs_have_equal_length(a__     )     )
      self.assertFalse(_inputs_have_equal_length(a__     )     )

      # truncate to smallest with np
      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[0]     )					, return_tensors='''np'''					, truncation=a__					, )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[0]     )					, return_tensors='''np'''     )
      __magic_name__		  =							input_a[input_name]

      self.assertTrue(_inputs_have_equal_length(a__     )     )
      self.assertTrue(input_a.shape[1] == len(speech_inputs[0]     )     )

      # since truncation forces padding to be smaller than longest input
      # function can't return `np.ndarray`, but has to return list
      self.assertFalse(_inputs_have_equal_length(a__     )     )

      # truncate to middle
      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[1]     )					, truncation=a__					, return_tensors='''np'''					, )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[1]     )					, truncation=a__     )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[1]     )					, return_tensors='''np'''     )
      __magic_name__		  =							input_a[input_name]

      self.assertTrue(input_a.shape[1] == len(speech_inputs[1]     )     )
      self.assertTrue(_inputs_have_equal_length(a__     )     )
      self.assertTrue(_inputs_have_equal_length(a__     )     )
      self.assertTrue(_inputs_are_equal(a__					, a__     )     )

      # since truncation forces padding to be smaller than longest input
      # function can't return `np.ndarray`, but has to return list
      self.assertFalse(_inputs_have_equal_length(a__     )     )
      self.assertTrue(len(input_a[-1]     ) == len(speech_inputs[-1]     )     )

      # padding has to be max_length when setting `truncation=True`
      with self.assertRaises(a__     ):
           feat_extract.pad(a__					, truncation=a__     )[input_name]

      # padding has to be max_length when setting `truncation=True`
      with self.assertRaises(a__     ):
           feat_extract.pad(a__					, padding='''longest'''					, truncation=a__     )[input_name]

      # padding has to be max_length when setting `truncation=True`
      with self.assertRaises(a__     ):
           feat_extract.pad(a__					, padding='''longest'''					, truncation=a__     )[input_name]

      # max_length parameter has to be provided when setting `truncation=True` and padding="max_length"
      with self.assertRaises(a__     ):
           feat_extract.pad(a__					, padding='''max_length'''					, truncation=a__     )[input_name]

      # test truncation for `pad_to_multiple_of` for List[int] + numpy
      __magic_name__		  =							12
      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[0]     )					, pad_to_multiple_of=a__					, truncation=a__					, )
      __magic_name__		  =							input_a[input_name]

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=len(speech_inputs[0]     )					, pad_to_multiple_of=a__					, )
      __magic_name__		  =							input_a[input_name]

      # retrieve expected_length as multiple of pad_to_multiple_of
      __magic_name__		  =							len(speech_inputs[0]     )
      if expected_length % pad_to_multiple_of != 0:
           __magic_name__		  =							((len(speech_inputs[0]     ) // pad_to_multiple_of) + 1) * pad_to_multiple_of

      self.assertTrue(len(input_a[0]     ) == expected_length     )
      self.assertTrue(_inputs_have_equal_length(a__     )     )
      self.assertFalse(_inputs_have_equal_length(a__     )     )



 def 					snake_case__    (       self						:       Tuple     ):
      self._check_padding(numpify=a__     )



 def 					snake_case__    (       self						:       int     ):
      self._check_padding(numpify=a__     )



 def 					snake_case__    (       self						:       str     ):
      self._check_truncation(numpify=a__     )



 def 					snake_case__    (       self						:       List[str]     ):
      self._check_truncation(numpify=a__     )



 @require_torch
 def 					snake_case__    (       self						:       int     ):
      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common()
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}     )

      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''					, return_tensors='''np'''     )[input_name]
      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''					, return_tensors='''pt'''     )[input_name]

      self.assertTrue(abs(input_np.astype(np.floataa     ).sum() - input_pt.numpy().astype(np.floataa     ).sum()     ) < 1E-2     )



 @require_tf
 def 					snake_case__    (       self						:       Optional[Any]     ):
      __magic_name__		  =							self.feature_extraction_class(**self.feat_extract_dict     )
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common()
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}     )

      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''					, return_tensors='''np'''     )[input_name]
      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''					, return_tensors='''tf'''     )[input_name]

      self.assertTrue(abs(input_np.astype(np.floataa     ).sum() - input_tf.numpy().astype(np.floataa     ).sum()     ) < 1E-2     )



 def 					snake_case__    (       self						:       Any     ):
      __magic_name__		  =							self.feat_extract_dict
      __magic_name__		  =							True
      __magic_name__		  =							self.feature_extraction_class(**a__     )
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common()
      __magic_name__		  =							[len(a__     ) for x in speech_inputs]
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}     )

      __magic_name__		  =							feat_extract.pad(a__					, padding='''longest'''					, return_tensors='''np'''     )
      self.assertIn('''attention_mask'''					, a__     )
      self.assertListEqual(list(processed.attention_mask.shape     )					, list(processed[input_name].shape[:2]     )     )
      self.assertListEqual(processed.attention_mask.sum(-1     ).tolist()					, a__     )



 def 					snake_case__    (       self						:       int     ):
      __magic_name__		  =							self.feat_extract_dict
      __magic_name__		  =							True
      __magic_name__		  =							self.feature_extraction_class(**a__     )
      __magic_name__		  =							self.feat_extract_tester.prepare_inputs_for_common()
      __magic_name__		  =							[len(a__     ) for x in speech_inputs]
      __magic_name__		  =							feat_extract.model_input_names[0]

      __magic_name__		  =							BatchFeature({input_name: speech_inputs}     )
      __magic_name__		  =							min(a__     )

      __magic_name__		  =							feat_extract.pad(
          a__					, padding='''max_length'''					, max_length=a__					, truncation=a__					, return_tensors='''np'''     )
      self.assertIn('''attention_mask'''					, a__     )
      self.assertListEqual(
          list(processed_pad.attention_mask.shape     )					, [processed_pad[input_name].shape[0], max_length]     )
      self.assertListEqual(
          processed_pad.attention_mask[:, :max_length].sum(-1     ).tolist()					, [max_length for x in speech_inputs]     )










'''simple docstring'''






import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
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    __magic_name__				(						lowerCAmelCase   ,unittest.TestCase							):
       UpperCAmelCase		 =KandinskyImgaImgPipeline
       UpperCAmelCase		 =["prompt", "image_embeds", "negative_image_embeds", "image"]
       UpperCAmelCase		 =[
           "prompt",
           "negative_prompt",
           "image_embeds",
           "negative_image_embeds",
           "image",
       ]
       UpperCAmelCase		 =[
           "generator",
           "height",
           "width",
           "strength",
           "guidance_scale",
           "negative_prompt",
           "num_inference_steps",
           "return_dict",
           "guidance_scale",
           "num_images_per_prompt",
           "output_type",
           "return_dict",
       ]
       UpperCAmelCase		 =False






       @property
       def      lowerCAmelCase						(     self)		->    str:




          '''simple docstring'''
          return 3_2






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




          '''simple docstring'''
          return 3_2






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




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






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




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






       @property
       def      lowerCAmelCase						(     self)		->    Tuple:




          '''simple docstring'''
          return 1_0_0






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




          '''simple docstring'''
          _UpperCAmelCase  :  int				       =XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base')
          return tokenizer






       @property
       def      lowerCAmelCase						(     self)		->    Dict:




          '''simple docstring'''
          torch.manual_seed(0)
          _UpperCAmelCase  :  Optional[Any]				       =MCLIPConfig(
              numDims=self.cross_attention_dim    ,				transformerDimensions=self.text_embedder_hidden_size    ,				hidden_size=self.text_embedder_hidden_size    ,				intermediate_size=3_7    ,				num_attention_heads=4    ,				num_hidden_layers=5    ,				vocab_size=1_0_0_5    ,				)

          _UpperCAmelCase  :  List[Any]				       =MultilingualCLIP(snake_case)
          _UpperCAmelCase  :  List[Any]				       =text_encoder.eval()

          return text_encoder






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




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

          _UpperCAmelCase  :  Union[str, Any]				       ={
              'in_channels': 4,
              # Out channels is double in channels because predicts mean and variance
              'out_channels': 8,
              'addition_embed_type': 'text_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': 'text_image_proj',
              'cross_attention_dim': self.cross_attention_dim,
              'attention_head_dim': 4,
              'resnet_time_scale_shift': 'scale_shift',
              'class_embed_type': None,
          }

          _UpperCAmelCase  :  Tuple				       =UNetaDConditionModel(**snake_case)
          return model






       @property
       def      lowerCAmelCase						(     self)		->    List[Any]:




          '''simple docstring'''
          return {
              "block_out_channels": [3_2, 6_4],
              "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": 1_2,
              "out_channels": 3,
              "up_block_types": [
                  "AttnUpDecoderBlock2D",
                  "UpDecoderBlock2D",
              ],
              "vq_embed_dim": 4,
          }






       @property
       def      lowerCAmelCase						(     self)		->    int:




          '''simple docstring'''
          torch.manual_seed(0)
          _UpperCAmelCase  :  List[Any]				       =VQModel(**self.dummy_movq_kwargs)
          return model






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




          '''simple docstring'''
          _UpperCAmelCase  :  Tuple				       =self.dummy_text_encoder
          _UpperCAmelCase  :  Any				       =self.dummy_tokenizer
          _UpperCAmelCase  :  List[str]				       =self.dummy_unet
          _UpperCAmelCase  :  Union[str, Any]				       =self.dummy_movq

          _UpperCAmelCase  :  List[str]				       ={
              'num_train_timesteps': 1_0_0_0,
              'beta_schedule': 'linear',
              'beta_start': 0.0_00_85,
              'beta_end': 0.0_12,
              'clip_sample': False,
              'set_alpha_to_one': False,
              'steps_offset': 0,
              'prediction_type': 'epsilon',
              'thresholding': False,
          }

          _UpperCAmelCase  :  Dict				       =DDIMScheduler(**snake_case)

          _UpperCAmelCase  :  Optional[int]				       ={
              'text_encoder': text_encoder,
              'tokenizer': tokenizer,
              'unet': unet,
              'scheduler': scheduler,
              'movq': movq,
          }

          return components






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case=0)		->    int:




          '''simple docstring'''
          _UpperCAmelCase  :  List[Any]				       =floats_tensor((1, self.cross_attention_dim)    ,				rng=random.Random(snake_case)).to(snake_case)
          _UpperCAmelCase  :  Tuple				       =floats_tensor((1, self.cross_attention_dim)    ,				rng=random.Random(seed + 1)).to(snake_case)
          # create init_image
          _UpperCAmelCase  :  Dict				       =floats_tensor((1, 3, 6_4, 6_4)    ,				rng=random.Random(snake_case)).to(snake_case)
          _UpperCAmelCase  :  Optional[int]				       =image.cpu().permute(0    ,				2    ,				3    ,				1)[0]
          _UpperCAmelCase  :  List[Any]				       =Image.fromarray(np.uinta(snake_case)).convert('RGB').resize((2_5_6, 2_5_6))

          if str(snake_case).startswith('mps'):
             _UpperCAmelCase  :  str				       =torch.manual_seed(snake_case)
          else:
             _UpperCAmelCase  :  Optional[Any]				       =torch.Generator(device=snake_case).manual_seed(snake_case)
          _UpperCAmelCase  :  str				       ={
              'prompt': 'horse',
              'image': init_image,
              'image_embeds': image_embeds,
              'negative_image_embeds': negative_image_embeds,
              'generator': generator,
              'height': 6_4,
              'width': 6_4,
              'num_inference_steps': 1_0,
              'guidance_scale': 7.0,
              'strength': 0.2,
              'output_type': 'np',
          }
          return inputs






       def      lowerCAmelCase						(     self)		->    str:




          '''simple docstring'''
          _UpperCAmelCase  :  List[Any]				       ='cpu'

          _UpperCAmelCase  :  Dict				       =self.get_dummy_components()

          _UpperCAmelCase  :  Optional[Any]				       =self.pipeline_class(**snake_case)
          _UpperCAmelCase  :  List[str]				       =pipe.to(snake_case)

          pipe.set_progress_bar_config(disable=snake_case)

          _UpperCAmelCase  :  List[Any]				       =pipe(**self.get_dummy_inputs(snake_case))
          _UpperCAmelCase  :  List[str]				       =output.images

          _UpperCAmelCase  :  Any				       =pipe(
              **self.get_dummy_inputs(snake_case)    ,				return_dict=snake_case    ,				)[0]

          _UpperCAmelCase  :  Any				       =image[0, -3:, -3:, -1]
          _UpperCAmelCase  :  Tuple				       =image_from_tuple[0, -3:, -3:, -1]

          assert image.shape == (1, 6_4, 6_4, 3)

          _UpperCAmelCase  :  List[Any]				       =np.array(
              [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33])
          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    __magic_name__				(						unittest.TestCase							):






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




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






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




          '''simple docstring'''
          _UpperCAmelCase  :  Tuple				       =load_numpy(
              'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
              '/kandinsky/kandinsky_img2img_frog.npy')

          _UpperCAmelCase  :  List[Any]				       =load_image(
              'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png')
          _UpperCAmelCase  :  Union[str, Any]				       ='A red cartoon frog, 4k'

          _UpperCAmelCase  :  Union[str, Any]				       =KandinskyPriorPipeline.from_pretrained(
              'kandinsky-community/kandinsky-2-1-prior'    ,				torch_dtype=torch.floataa)
          pipe_prior.to(snake_case)

          _UpperCAmelCase  :  Optional[Any]				       =KandinskyImgaImgPipeline.from_pretrained(
              'kandinsky-community/kandinsky-2-1'    ,				torch_dtype=torch.floataa)
          _UpperCAmelCase  :  Tuple				       =pipeline.to(snake_case)

          pipeline.set_progress_bar_config(disable=snake_case)

          _UpperCAmelCase  :  List[str]				       =torch.Generator(device='cpu').manual_seed(0)
          _UpperCAmelCase       ,			_UpperCAmelCase  :  List[Any]				       =pipe_prior(
              snake_case    ,				generator=snake_case    ,				num_inference_steps=5    ,				negative_prompt=''    ,				).to_tuple()

          _UpperCAmelCase  :  str				       =pipeline(
              snake_case    ,				image=snake_case    ,				image_embeds=snake_case    ,				negative_image_embeds=snake_case    ,				generator=snake_case    ,				num_inference_steps=1_0_0    ,				height=7_6_8    ,				width=7_6_8    ,				strength=0.2    ,				output_type='np'    ,				)

          _UpperCAmelCase  :  Any				       =output.images[0]

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

          assert_mean_pixel_difference(snake_case    ,				snake_case)

