




"""simple docstring"""
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  _SCREAMING_SNAKE_CASE       :



 '''simple docstring'''





 def __init__(self					,     lowerCAmelCase__					,     lowerCAmelCase__=2					,     lowerCAmelCase__=32					,     lowerCAmelCase__=16					,     lowerCAmelCase__=3					,     lowerCAmelCase__=True					,     lowerCAmelCase__=True					,     lowerCAmelCase__=32					,     lowerCAmelCase__=4					,     lowerCAmelCase__=[0, 1, 2, 3]					,     lowerCAmelCase__=4					,     lowerCAmelCase__=37					,     lowerCAmelCase__="gelu"					,     lowerCAmelCase__=0.1					,     lowerCAmelCase__=0.1					,     lowerCAmelCase__=0.02					,     lowerCAmelCase__=3					,     lowerCAmelCase__=False					,     lowerCAmelCase__=None					,     ):

  '''simple docstring'''







  _UpperCamelCase      :	int					      =  parent
  _UpperCamelCase      :	Union[str, Any]					      =  batch_size
  _UpperCamelCase      :	Optional[int]					      =  image_size
  _UpperCamelCase      :	Any					      =  patch_size
  _UpperCamelCase      :	List[str]					      =  num_channels
  _UpperCamelCase      :	int					      =  is_training
  _UpperCamelCase      :	List[str]					      =  use_labels
  _UpperCamelCase      :	List[str]					      =  hidden_size
  _UpperCamelCase      :	Any					      =  num_hidden_layers
  _UpperCamelCase      :	Optional[int]					      =  backbone_out_indices
  _UpperCamelCase      :	Union[str, Any]					      =  num_attention_heads
  _UpperCamelCase      :	List[str]					      =  intermediate_size
  _UpperCamelCase      :	Any					      =  hidden_act
  _UpperCamelCase      :	Tuple					      =  hidden_dropout_prob
  _UpperCamelCase      :	List[str]					      =  attention_probs_dropout_prob
  _UpperCamelCase      :	Union[str, Any]					      =  initializer_range
  _UpperCamelCase      :	List[Any]					      =  num_labels
  _UpperCamelCase      :	Union[str, Any]					      =  scope
  _UpperCamelCase      :	List[str]					      =  is_hybrid
  # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
  _UpperCamelCase      :	List[str]					      =  (image_size // patch_size) ** 2
  _UpperCamelCase      :	int					      =  num_patches + 1






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	Optional[int]					      =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

  _UpperCamelCase      :	str					      =  self.get_config()

  return config, pixel_values, labels






 def lowercase_      (self   ):

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

  '''simple docstring'''







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






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

  '''simple docstring'''







  _UpperCamelCase      :	List[str]					      =  self.num_labels
  _UpperCamelCase      :	Optional[int]					      =  DPTForDepthEstimation(lowerCAmelCase__   )
  model.to(lowerCAmelCase__   )
  model.eval()
  _UpperCamelCase      :	Union[str, Any]					      =  model(lowerCAmelCase__   )
  self.parent.assertEqual(result.predicted_depth.shape					,     (self.batch_size, self.image_size, self.image_size)   )






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

  '''simple docstring'''







  _UpperCamelCase      :	Dict					      =  self.num_labels
  _UpperCamelCase      :	List[str]					      =  DPTForSemanticSegmentation(lowerCAmelCase__   )
  model.to(lowerCAmelCase__   )
  model.eval()
  _UpperCamelCase      :	str					      =  model(lowerCAmelCase__					,     labels=lowerCAmelCase__   )
  self.parent.assertEqual(
      result.logits.shape					,     (self.batch_size, self.num_labels, self.image_size, self.image_size)   )






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	Tuple					      =  self.prepare_config_and_inputs()
  _UpperCamelCase      ,	_UpperCamelCase      ,	_UpperCamelCase      :	List[str]					      =  config_and_inputs
  _UpperCamelCase      :	List[Any]					      =  {"pixel_values": pixel_values}
  return config, inputs_dict







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



 '''simple docstring'''





 __UpperCAmelCase		   =							(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
 __UpperCAmelCase		   =							(
     {
         """depth-estimation""": DPTForDepthEstimation,
         """feature-extraction""": DPTModel,
         """image-segmentation""": DPTForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 __UpperCAmelCase		   =							False
 __UpperCAmelCase		   =							False
 __UpperCAmelCase		   =							False






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	Optional[int]					      =  DPTModelTester(self   )
  _UpperCamelCase      :	List[str]					      =  ConfigTester(self					,     config_class=lowerCAmelCase__					,     has_text_modality=lowerCAmelCase__					,     hidden_size=37   )






 def lowercase_      (self   ):

  '''simple docstring'''







  self.config_tester.run_common_tests()






 @unittest.skip(reason="DPT does not use inputs_embeds"   )
 def lowercase_      (self   ):

  '''simple docstring'''







  pass






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      ,	_UpperCamelCase      :	Any					      =  self.model_tester.prepare_config_and_inputs_for_common()

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






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      ,	_UpperCamelCase      :	int					      =  self.model_tester.prepare_config_and_inputs_for_common()

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

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






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	int					      =  self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*lowerCAmelCase__   )






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	List[str]					      =  self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_depth_estimation(*lowerCAmelCase__   )






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	str					      =  self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase__   )






 def lowercase_      (self   ):

  '''simple docstring'''







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

   _UpperCamelCase      ,	_UpperCamelCase      :	List[Any]					      =  self.model_tester.prepare_config_and_inputs_for_common()
   _UpperCamelCase      :	List[str]					      =  True

   if model_class in get_values(lowerCAmelCase__   ):
    continue

   _UpperCamelCase      :	List[str]					      =  model_class(lowerCAmelCase__   )
   model.to(lowerCAmelCase__   )
   model.train()
   _UpperCamelCase      :	str					      =  self._prepare_for_class(lowerCAmelCase__					,     lowerCAmelCase__					,     return_labels=lowerCAmelCase__   )
   _UpperCamelCase      :	Optional[Any]					      =  model(**lowerCAmelCase__   ).loss
   loss.backward()






 def lowercase_      (self   ):

  '''simple docstring'''







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

   _UpperCamelCase      ,	_UpperCamelCase      :	Any					      =  self.model_tester.prepare_config_and_inputs_for_common()
   _UpperCamelCase      :	int					      =  False
   _UpperCamelCase      :	List[Any]					      =  True

   if model_class in get_values(lowerCAmelCase__   ) or not model_class.supports_gradient_checkpointing:
    continue
   _UpperCamelCase      :	Union[str, Any]					      =  model_class(lowerCAmelCase__   )
   model.to(lowerCAmelCase__   )
   model.gradient_checkpointing_enable()
   model.train()
   _UpperCamelCase      :	Optional[int]					      =  self._prepare_for_class(lowerCAmelCase__					,     lowerCAmelCase__					,     return_labels=lowerCAmelCase__   )
   _UpperCamelCase      :	Dict					      =  model(**lowerCAmelCase__   ).loss
   loss.backward()






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      ,	_UpperCamelCase      :	List[Any]					      =  self.model_tester.prepare_config_and_inputs_for_common()

  _UpperCamelCase      :	Any					      =  _config_zero_init(lowerCAmelCase__   )
  for model_class in self.all_model_classes:
   _UpperCamelCase      :	str					      =  model_class(config=lowerCAmelCase__   )
   # Skip the check for the backbone
   _UpperCamelCase      :	List[Any]					      =  []
   for name, module in model.named_modules():
    if module.__class__.__name__ == "DPTViTHybridEmbeddings":
     _UpperCamelCase      :	Union[str, Any]					      =  [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 lowercase_      (self   ):

  '''simple docstring'''







  pass






 @slow
 def lowercase_      (self   ):

  '''simple docstring'''







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






def 				__lowerCAmelCase					(					)    ->       List[str]:
 _UpperCamelCase      :	str					      =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
 return image







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



 '''simple docstring'''





 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	str					      =  DPTImageProcessor.from_pretrained("Intel/dpt-large"   )
  _UpperCamelCase      :	Dict					      =  DPTForDepthEstimation.from_pretrained("Intel/dpt-large"   ).to(lowerCAmelCase__   )

  _UpperCamelCase      :	Tuple					      =  prepare_img()
  _UpperCamelCase      :	Union[str, Any]					      =  image_processor(images=lowerCAmelCase__					,     return_tensors="pt"   ).to(lowerCAmelCase__   )

  # forward pass
  with torch.no_grad():
   _UpperCamelCase      :	Union[str, Any]					      =  model(**lowerCAmelCase__   )
   _UpperCamelCase      :	Optional[int]					      =  outputs.predicted_depth

  # verify the predicted depth
  _UpperCamelCase      :	List[str]					      =  torch.Size((1, 3_84, 3_84)   )
  self.assertEqual(predicted_depth.shape					,     lowerCAmelCase__   )

  _UpperCamelCase      :	Tuple					      =  torch.tensor(
      [[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]]   ).to(lowerCAmelCase__   )

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






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	Union[str, Any]					      =  DPTImageProcessor.from_pretrained("Intel/dpt-large-ade"   )
  _UpperCamelCase      :	Tuple					      =  DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade"   ).to(lowerCAmelCase__   )

  _UpperCamelCase      :	Optional[Any]					      =  prepare_img()
  _UpperCamelCase      :	List[str]					      =  image_processor(images=lowerCAmelCase__					,     return_tensors="pt"   ).to(lowerCAmelCase__   )

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

  # verify the logits
  _UpperCamelCase      :	Dict					      =  torch.Size((1, 1_50, 4_80, 4_80)   )
  self.assertEqual(outputs.logits.shape					,     lowerCAmelCase__   )

  _UpperCamelCase      :	List[Any]					      =  torch.tensor(
      [[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]]   ).to(lowerCAmelCase__   )

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






 def lowercase_      (self   ):

  '''simple docstring'''







  _UpperCamelCase      :	List[Any]					      =  DPTImageProcessor.from_pretrained("Intel/dpt-large-ade"   )
  _UpperCamelCase      :	List[str]					      =  DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade"   ).to(lowerCAmelCase__   )

  _UpperCamelCase      :	str					      =  prepare_img()
  _UpperCamelCase      :	str					      =  image_processor(images=lowerCAmelCase__					,     return_tensors="pt"   ).to(lowerCAmelCase__   )

  # forward pass
  with torch.no_grad():
   _UpperCamelCase      :	Optional[int]					      =  model(**lowerCAmelCase__   )

  _UpperCamelCase      :	Optional[Any]					      =  outputs.logits.detach().cpu()

  _UpperCamelCase      :	Optional[int]					      =  image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase__					,     target_sizes=[(5_00, 3_00)]   )
  _UpperCamelCase      :	List[str]					      =  torch.Size((5_00, 3_00)   )
  self.assertEqual(segmentation[0].shape					,     lowerCAmelCase__   )

  _UpperCamelCase      :	str					      =  image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase__   )
  _UpperCamelCase      :	List[str]					      =  torch.Size((4_80, 4_80)   )
  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__   )



