






import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
		from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import DPTImageProcessor



class  __UpperCAmelCase						:







			def __init__(      self:    str ,      UpperCAmelCase_:    Any ,      UpperCAmelCase_:    Any=2 ,      UpperCAmelCase_:    Union[str, Any]=32 ,      UpperCAmelCase_:    int=16 ,      UpperCAmelCase_:    Dict=3 ,      UpperCAmelCase_:    Dict=True ,      UpperCAmelCase_:    Optional[int]=True ,      UpperCAmelCase_:    Union[str, Any]=32 ,      UpperCAmelCase_:    Tuple=4 ,      UpperCAmelCase_:    List[Any]=[0, 1, 2, 3] ,      UpperCAmelCase_:    Optional[int]=4 ,      UpperCAmelCase_:    Any=37 ,      UpperCAmelCase_:    Dict="gelu" ,      UpperCAmelCase_:    Union[str, Any]=0.1 ,      UpperCAmelCase_:    Any=0.1 ,      UpperCAmelCase_:    Any=0.02 ,      UpperCAmelCase_:    List[str]=3 ,      UpperCAmelCase_:    str=False ,      UpperCAmelCase_:    int=None ,      ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    parent
									_SCREAMING_SNAKE_CASE       =    batch_size
									_SCREAMING_SNAKE_CASE       =    image_size
									_SCREAMING_SNAKE_CASE       =    patch_size
									_SCREAMING_SNAKE_CASE       =    num_channels
									_SCREAMING_SNAKE_CASE       =    is_training
									_SCREAMING_SNAKE_CASE       =    use_labels
									_SCREAMING_SNAKE_CASE       =    hidden_size
									_SCREAMING_SNAKE_CASE       =    num_hidden_layers
									_SCREAMING_SNAKE_CASE       =    backbone_out_indices
									_SCREAMING_SNAKE_CASE       =    num_attention_heads
									_SCREAMING_SNAKE_CASE       =    intermediate_size
									_SCREAMING_SNAKE_CASE       =    hidden_act
									_SCREAMING_SNAKE_CASE       =    hidden_dropout_prob
									_SCREAMING_SNAKE_CASE       =    attention_probs_dropout_prob
									_SCREAMING_SNAKE_CASE       =    initializer_range
									_SCREAMING_SNAKE_CASE       =    num_labels
									_SCREAMING_SNAKE_CASE       =    scope
									_SCREAMING_SNAKE_CASE       =    is_hybrid
									# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
									_SCREAMING_SNAKE_CASE       =    (image_size // patch_size) ** 2
									_SCREAMING_SNAKE_CASE       =    num_patches + 1







			def 				UpperCamelCase (      self:    str	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

									_SCREAMING_SNAKE_CASE       =    None
									if self.use_labels:
															_SCREAMING_SNAKE_CASE       =    ids_tensor([self.batch_size, self.image_size, self.image_size] ,      self.num_labels	)

									_SCREAMING_SNAKE_CASE       =    self.get_config()

									return config, pixel_values, labels







			def 				UpperCamelCase (      self:    Any	):







									'''simple docstring'''




									return DPTConfig(
									    image_size=self.image_size ,      patch_size=self.patch_size ,      num_channels=self.num_channels ,      hidden_size=self.hidden_size ,      num_hidden_layers=self.num_hidden_layers ,      backbone_out_indices=self.backbone_out_indices ,      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 ,      is_decoder=lowerCAmelCase__ ,      initializer_range=self.initializer_range ,      is_hybrid=self.is_hybrid ,      )







			def 				UpperCamelCase (      self:    Optional[int] ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    Union[str, Any] ,      UpperCAmelCase_:    Union[str, Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTModel(config=lowerCAmelCase__	)
									model.to(lowerCAmelCase__	)
									model.eval()
									_SCREAMING_SNAKE_CASE       =    model(lowerCAmelCase__	)
									self.parent.assertEqual(result.last_hidden_state.shape ,      (self.batch_size, self.seq_length, self.hidden_size)	)







			def 				UpperCamelCase (      self:    Tuple ,      UpperCAmelCase_:    List[str] ,      UpperCAmelCase_:    Tuple ,      UpperCAmelCase_:    Any	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.num_labels
									_SCREAMING_SNAKE_CASE       =    DPTForDepthEstimation(lowerCAmelCase__	)
									model.to(lowerCAmelCase__	)
									model.eval()
									_SCREAMING_SNAKE_CASE       =    model(lowerCAmelCase__	)
									self.parent.assertEqual(result.predicted_depth.shape ,      (self.batch_size, self.image_size, self.image_size)	)







			def 				UpperCamelCase (      self:    List[str] ,      UpperCAmelCase_:    Optional[Any] ,      UpperCAmelCase_:    int ,      UpperCAmelCase_:    str	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.num_labels
									_SCREAMING_SNAKE_CASE       =    DPTForSemanticSegmentation(lowerCAmelCase__	)
									model.to(lowerCAmelCase__	)
									model.eval()
									_SCREAMING_SNAKE_CASE       =    model(lowerCAmelCase__ ,      labels=lowerCAmelCase__	)
									self.parent.assertEqual(
									    result.logits.shape ,      (self.batch_size, self.num_labels, self.image_size, self.image_size)	)







			def 				UpperCamelCase (      self:    int	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.prepare_config_and_inputs()
									_SCREAMING_SNAKE_CASE       =    config_and_inputs
									_SCREAMING_SNAKE_CASE       =    {"pixel_values": pixel_values}
									return config, inputs_dict



@require_torch
class  __UpperCAmelCase						(SCREAMING_SNAKE_CASE__			,SCREAMING_SNAKE_CASE__			,unittest.TestCase       ):
			__snake_case							: Any							=				(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
			__snake_case							: List[str]							=				(
			    {
			        "depth-estimation": DPTForDepthEstimation,
			        "feature-extraction": DPTModel,
			        "image-segmentation": DPTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			__snake_case							: Optional[int]							=				False
			__snake_case							: Any							=				False
			__snake_case							: Dict							=				False







			def 				UpperCamelCase (      self:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTModelTester(self	)
									_SCREAMING_SNAKE_CASE       =    ConfigTester(self ,      config_class=lowerCAmelCase__ ,      has_text_modality=lowerCAmelCase__ ,      hidden_size=37	)







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									self.config_tester.run_common_tests()







			@unittest.skip(reason="""DPT does not use inputs_embeds"""	)
			def 				UpperCamelCase (      self:    Optional[Any]	):







									'''simple docstring'''




									pass







			def 				UpperCamelCase (      self:    List[str]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    model_class(lowerCAmelCase__	)
															self.assertIsInstance(model.get_input_embeddings() ,      (nn.Module)	)
															_SCREAMING_SNAKE_CASE       =    model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowerCAmelCase__ ,      nn.Linear	)	)







			def 				UpperCamelCase (      self:    Optional[int]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    model_class(lowerCAmelCase__	)
															_SCREAMING_SNAKE_CASE       =    inspect.signature(model.forward	)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															_SCREAMING_SNAKE_CASE       =    [*signature.parameters.keys()]

															_SCREAMING_SNAKE_CASE       =    ["pixel_values"]
															self.assertListEqual(arg_names[:1] ,      lowerCAmelCase__	)







			def 				UpperCamelCase (      self:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase__	)







			def 				UpperCamelCase (      self:    int	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_depth_estimation(*lowerCAmelCase__	)







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase__	)







			def 				UpperCamelCase (      self:    Optional[Any]	):







									'''simple docstring'''




									for model_class in self.all_model_classes:
															if model_class.__name__ == "DPTForDepthEstimation":
																					continue

															_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()
															_SCREAMING_SNAKE_CASE       =    True

															if model_class in get_values(lowerCAmelCase__	):
																					continue

															_SCREAMING_SNAKE_CASE       =    model_class(lowerCAmelCase__	)
															model.to(lowerCAmelCase__	)
															model.train()
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCAmelCase__ ,      lowerCAmelCase__ ,      return_labels=lowerCAmelCase__	)
															_SCREAMING_SNAKE_CASE       =    model(**lowerCAmelCase__	).loss
															loss.backward()







			def 				UpperCamelCase (      self:    int	):







									'''simple docstring'''




									for model_class in self.all_model_classes:
															if model_class.__name__ == "DPTForDepthEstimation":
																					continue

															_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()
															_SCREAMING_SNAKE_CASE       =    False
															_SCREAMING_SNAKE_CASE       =    True

															if model_class in get_values(lowerCAmelCase__	) or not model_class.supports_gradient_checkpointing:
																					continue
															_SCREAMING_SNAKE_CASE       =    model_class(lowerCAmelCase__	)
															model.to(lowerCAmelCase__	)
															model.gradient_checkpointing_enable()
															model.train()
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCAmelCase__ ,      lowerCAmelCase__ ,      return_labels=lowerCAmelCase__	)
															_SCREAMING_SNAKE_CASE       =    model(**lowerCAmelCase__	).loss
															loss.backward()







			def 				UpperCamelCase (      self:    Union[str, Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									_SCREAMING_SNAKE_CASE       =    _config_zero_init(lowerCAmelCase__	)
									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    model_class(config=lowerCAmelCase__	)
															# Skip the check for the backbone
															_SCREAMING_SNAKE_CASE       =    []
															for name, module in model.named_modules():
																					if module.__class__.__name__ == "DPTViTHybridEmbeddings":
																											_SCREAMING_SNAKE_CASE       =    [F'{name}.{key}' for key in module.state_dict().keys()]
																											break

															for name, param in model.named_parameters():
																					if param.requires_grad:
																											if name in backbone_params:
																																	continue
																											self.assertIn(
																											    ((param.data.mean() * 1E9).round() / 1E9).item() ,      [0.0, 1.0] ,      msg=F'Parameter {name} of model {model_class} seems not properly initialized' ,      )







			@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""	)
			def 				UpperCamelCase (      self:    Any	):







									'''simple docstring'''




									pass







			@slow
			def 				UpperCamelCase (      self:    Dict	):







									'''simple docstring'''




									for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE       =    DPTModel.from_pretrained(lowerCAmelCase__	)
															self.assertIsNotNone(lowerCAmelCase__	)

def 			__lowerCamelCase     (						)				->    List[str]:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE       =    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
						return image




@require_torch
@require_vision
@slow
class  __UpperCAmelCase						(unittest.TestCase       ):







			def 				UpperCamelCase (      self:    Union[str, Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTImageProcessor.from_pretrained("""Intel/dpt-large"""	)
									_SCREAMING_SNAKE_CASE       =    DPTForDepthEstimation.from_pretrained("""Intel/dpt-large"""	).to(lowerCAmelCase__	)

									_SCREAMING_SNAKE_CASE       =    prepare_img()
									_SCREAMING_SNAKE_CASE       =    image_processor(images=lowerCAmelCase__ ,      return_tensors="""pt"""	).to(lowerCAmelCase__	)

									# forward pass
									with torch.no_grad():
															_SCREAMING_SNAKE_CASE       =    model(**lowerCAmelCase__	)
															_SCREAMING_SNAKE_CASE       =    outputs.predicted_depth

									# verify the predicted depth
									_SCREAMING_SNAKE_CASE       =    torch.Size((1, 384, 384)	)
									self.assertEqual(predicted_depth.shape ,      lowerCAmelCase__	)

									_SCREAMING_SNAKE_CASE       =    torch.tensor(
									    [[6.31_99, 6.36_29, 6.41_48], [6.38_50, 6.36_15, 6.41_66], [6.35_19, 6.31_76, 6.35_75]]	).to(lowerCAmelCase__	)

									self.assertTrue(torch.allclose(outputs.predicted_depth[0, :3, :3] ,      lowerCAmelCase__ ,      atol=1E-4	)	)







			def 				UpperCamelCase (      self:    Optional[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""	)
									_SCREAMING_SNAKE_CASE       =    DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""	).to(lowerCAmelCase__	)

									_SCREAMING_SNAKE_CASE       =    prepare_img()
									_SCREAMING_SNAKE_CASE       =    image_processor(images=lowerCAmelCase__ ,      return_tensors="""pt"""	).to(lowerCAmelCase__	)

									# forward pass
									with torch.no_grad():
															_SCREAMING_SNAKE_CASE       =    model(**lowerCAmelCase__	)

									# verify the logits
									_SCREAMING_SNAKE_CASE       =    torch.Size((1, 150, 480, 480)	)
									self.assertEqual(outputs.logits.shape ,      lowerCAmelCase__	)

									_SCREAMING_SNAKE_CASE       =    torch.tensor(
									    [[4.04_80, 4.24_20, 4.43_60], [4.31_24, 4.56_93, 4.82_61], [4.57_68, 4.89_65, 5.21_63]]	).to(lowerCAmelCase__	)

									self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] ,      lowerCAmelCase__ ,      atol=1E-4	)	)







			def 				UpperCamelCase (      self:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""	)
									_SCREAMING_SNAKE_CASE       =    DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""	).to(lowerCAmelCase__	)

									_SCREAMING_SNAKE_CASE       =    prepare_img()
									_SCREAMING_SNAKE_CASE       =    image_processor(images=lowerCAmelCase__ ,      return_tensors="""pt"""	).to(lowerCAmelCase__	)

									# forward pass
									with torch.no_grad():
															_SCREAMING_SNAKE_CASE       =    model(**lowerCAmelCase__	)

									_SCREAMING_SNAKE_CASE       =    outputs.logits.detach().cpu()

									_SCREAMING_SNAKE_CASE       =    image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase__ ,      target_sizes=[(500, 300)]	)
									_SCREAMING_SNAKE_CASE       =    torch.Size((500, 300)	)
									self.assertEqual(segmentation[0].shape ,      lowerCAmelCase__	)

									_SCREAMING_SNAKE_CASE       =    image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase__	)
									_SCREAMING_SNAKE_CASE       =    torch.Size((480, 480)	)
									self.assertEqual(segmentation[0].shape ,      lowerCAmelCase__	)







"""simple docstring"""
import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
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  _SCREAMING_SNAKE_CASE       (     SCREAMING_SNAKE_CASE__			,				unittest.TestCase				):



 '''simple docstring'''





 __UpperCAmelCase		   =							KandinskyPipeline
 __UpperCAmelCase		   =							[
     """prompt""",
     """image_embeds""",
     """negative_image_embeds""",
 ]
 __UpperCAmelCase		   =							["""prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds"""]
 __UpperCAmelCase		   =							[
     """generator""",
     """height""",
     """width""",
     """latents""",
     """guidance_scale""",
     """negative_prompt""",
     """num_inference_steps""",
     """return_dict""",
     """guidance_scale""",
     """num_images_per_prompt""",
     """output_type""",
     """return_dict""",
 ]
 __UpperCAmelCase		   =							False






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  return 32






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  return 32






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  return self.time_input_dim






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  return self.time_input_dim * 4






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  return 1_00






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	Tuple					      =  XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base"   )
  return tokenizer






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  torch.manual_seed(0   )
  _UpperCamelCase      :	List[str]					      =  MCLIPConfig(
      numDims=self.cross_attention_dim					,     transformerDimensions=self.text_embedder_hidden_size					,     hidden_size=self.text_embedder_hidden_size					,     intermediate_size=37					,     num_attention_heads=4					,     num_hidden_layers=5					,     vocab_size=10_05					,     )

  _UpperCamelCase      :	Optional[Any]					      =  MultilingualCLIP(lowerCAmelCase__   )
  _UpperCamelCase      :	List[str]					      =  text_encoder.eval()

  return text_encoder






 @property
 def lowercase_      (self   ):

  '''simple docstring'''







  torch.manual_seed(0   )

  _UpperCamelCase      :	Dict					      =  {
      "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      :	int					      =  UNetaDConditionModel(**lowerCAmelCase__   )
  return model






 @property
 def lowercase_      (self   ):

  '''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 lowercase_      (self   ):

  '''simple docstring'''







  torch.manual_seed(0   )
  _UpperCamelCase      :	Dict					      =  VQModel(**self.dummy_movq_kwargs   )
  return model






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	List[str]					      =  self.dummy_text_encoder
  _UpperCamelCase      :	str					      =  self.dummy_tokenizer
  _UpperCamelCase      :	List[str]					      =  self.dummy_unet
  _UpperCamelCase      :	Tuple					      =  self.dummy_movq

  _UpperCamelCase      :	Dict					      =  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      :	Any					      =  {
      "text_encoder": text_encoder,
      "tokenizer": tokenizer,
      "unet": unet,
      "scheduler": scheduler,
      "movq": movq,
  }
  return components






 def lowercase_      (self					,     lowerCAmelCase__					,     lowerCAmelCase__=0   ):

  '''simple docstring'''







  _UpperCamelCase      :	Dict					      =  floats_tensor((1, self.cross_attention_dim)					,     rng=random.Random(lowerCAmelCase__   )   ).to(lowerCAmelCase__   )
  _UpperCamelCase      :	int					      =  floats_tensor((1, self.cross_attention_dim)					,     rng=random.Random(seed + 1   )   ).to(lowerCAmelCase__   )
  if str(lowerCAmelCase__   ).startswith("mps"   ):
   _UpperCamelCase      :	Optional[Any]					      =  torch.manual_seed(lowerCAmelCase__   )
  else:
   _UpperCamelCase      :	List[Any]					      =  torch.Generator(device=lowerCAmelCase__   ).manual_seed(lowerCAmelCase__   )
  _UpperCamelCase      :	Optional[Any]					      =  {
      "prompt": "horse",
      "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 lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	Optional[Any]					      =  "cpu"

  _UpperCamelCase      :	Any					      =  self.get_dummy_components()

  _UpperCamelCase      :	Tuple					      =  self.pipeline_class(**lowerCAmelCase__   )
  _UpperCamelCase      :	Optional[int]					      =  pipe.to(lowerCAmelCase__   )

  pipe.set_progress_bar_config(disable=lowerCAmelCase__   )

  _UpperCamelCase      :	Union[str, Any]					      =  pipe(**self.get_dummy_inputs(lowerCAmelCase__   )   )
  _UpperCamelCase      :	Union[str, Any]					      =  output.images

  _UpperCamelCase      :	str					      =  pipe(
      **self.get_dummy_inputs(lowerCAmelCase__   )					,     return_dict=lowerCAmelCase__					,     )[0]

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

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

  _UpperCamelCase      :	Union[str, Any]					      =  np.array(
      [0.32_8663, 1.0, 0.2321_6873, 1.0, 0.9271_7564, 0.463_9046, 0.9689_4777, 0.3171_3378, 0.629_3953]   )

  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				):



 '''simple docstring'''





 def lowercase_      (self   ):

  '''simple docstring'''







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






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	Tuple					      =  load_numpy(
      "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
      "/kandinsky/kandinsky_text2img_cat_fp16.npy"   )

  _UpperCamelCase      :	Optional[int]					      =  KandinskyPriorPipeline.from_pretrained(
      "kandinsky-community/kandinsky-2-1-prior"					,     torch_dtype=torch.floataa   )
  pipe_prior.to(lowerCAmelCase__   )

  _UpperCamelCase      :	List[str]					      =  KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1"					,     torch_dtype=torch.floataa   )
  _UpperCamelCase      :	List[Any]					      =  pipeline.to(lowerCAmelCase__   )
  pipeline.set_progress_bar_config(disable=lowerCAmelCase__   )

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

  _UpperCamelCase      :	str					      =  torch.Generator(device="cuda"   ).manual_seed(0   )
  _UpperCamelCase      ,	_UpperCamelCase      :	Optional[Any]					      =  pipe_prior(
      lowerCAmelCase__					,     generator=lowerCAmelCase__					,     num_inference_steps=5					,     negative_prompt=""					,     ).to_tuple()

  _UpperCamelCase      :	Optional[Any]					      =  torch.Generator(device="cuda"   ).manual_seed(0   )
  _UpperCamelCase      :	Any					      =  pipeline(
      lowerCAmelCase__					,     image_embeds=lowerCAmelCase__					,     negative_image_embeds=lowerCAmelCase__					,     generator=lowerCAmelCase__					,     num_inference_steps=1_00					,     output_type="np"					,     )

  _UpperCamelCase      :	Optional[Any]					      =  output.images[0]

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

  assert_mean_pixel_difference(lowerCAmelCase__					,     lowerCAmelCase__   )



