






"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import numpy as np
      import tensorflow as tf

      from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
      from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import MobileViTImageProcessor



class 						a_ (      snake_case_					):







      '''simple docstring'''

      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     int								=		self.config_class(**self.inputs_dict   )
       self.parent.assertTrue(hasattr(lowerCamelCase_,	'hidden_sizes'   )   )
       self.parent.assertTrue(hasattr(lowerCamelCase_,	'neck_hidden_sizes'   )   )
       self.parent.assertTrue(hasattr(lowerCamelCase_,	'num_attention_heads'   )   )



class 						a_ :







      '''simple docstring'''

      def __init__(self,	lowerCamelCase_,	lowerCamelCase_=1_3,	lowerCamelCase_=3_2,	lowerCamelCase_=2,	lowerCamelCase_=3,	lowerCamelCase_=6_4_0,	lowerCamelCase_=4,	lowerCamelCase_="silu",	lowerCamelCase_=3,	lowerCamelCase_=3_2,	lowerCamelCase_=0.1,	lowerCamelCase_=0.1,	lowerCamelCase_=0.1,	lowerCamelCase_=0.02,	lowerCamelCase_=True,	lowerCamelCase_=True,	lowerCamelCase_=1_0,	lowerCamelCase_=None,	):

       '''simple docstring'''



       lowerCamelCase__	:     Any								=		parent
       lowerCamelCase__	:     str								=		batch_size
       lowerCamelCase__	:     Dict								=		image_size
       lowerCamelCase__	:     Tuple								=		patch_size
       lowerCamelCase__	:     List[str]								=		num_channels
       lowerCamelCase__	:     List[Any]								=		last_hidden_size
       lowerCamelCase__	:     Optional[Any]								=		num_attention_heads
       lowerCamelCase__	:     Any								=		hidden_act
       lowerCamelCase__	:     Dict								=		conv_kernel_size
       lowerCamelCase__	:     List[Any]								=		output_stride
       lowerCamelCase__	:     List[Any]								=		hidden_dropout_prob
       lowerCamelCase__	:     List[str]								=		attention_probs_dropout_prob
       lowerCamelCase__	:     Dict								=		classifier_dropout_prob
       lowerCamelCase__	:     List[str]								=		use_labels
       lowerCamelCase__	:     Union[str, Any]								=		is_training
       lowerCamelCase__	:     Optional[int]								=		num_labels
       lowerCamelCase__	:     Dict								=		initializer_range
       lowerCamelCase__	:     int								=		scope




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

       lowerCamelCase__	:     List[Any]								=		None
       lowerCamelCase__	:     Optional[Any]								=		None
       if self.use_labels:
        lowerCamelCase__	:     Dict								=		ids_tensor([self.batch_size],	self.num_labels   )
        lowerCamelCase__	:     List[Any]								=		ids_tensor([self.batch_size, self.image_size, self.image_size],	self.num_labels   )

       lowerCamelCase__	:     List[str]								=		self.get_config()

       return config, pixel_values, labels, pixel_labels




      def      a__				(self   ):

       '''simple docstring'''



       return MobileViTConfig(
           image_size=self.image_size,	patch_size=self.patch_size,	num_channels=self.num_channels,	num_attention_heads=self.num_attention_heads,	hidden_act=self.hidden_act,	conv_kernel_size=self.conv_kernel_size,	output_stride=self.output_stride,	hidden_dropout_prob=self.hidden_dropout_prob,	attention_probs_dropout_prob=self.attention_probs_dropout_prob,	classifier_dropout_prob=self.classifier_dropout_prob,	initializer_range=self.initializer_range,	)




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		TFMobileViTModel(config=lowerCamelCase_   )
       lowerCamelCase__	:     Union[str, Any]								=		model(lowerCamelCase_,	training=lowerCamelCase_   )
       lowerCamelCase__	:     str								=		self.image_size // self.output_stride
       self.parent.assertEqual(
           result.last_hidden_state.shape,	(self.batch_size, self.last_hidden_size, expected_height, expected_width)   )




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     int								=		self.num_labels
       lowerCamelCase__	:     Optional[int]								=		TFMobileViTForImageClassification(lowerCamelCase_   )
       lowerCamelCase__	:     Optional[Any]								=		model(lowerCamelCase_,	labels=lowerCamelCase_,	training=lowerCamelCase_   )
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.num_labels)   )




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		self.num_labels
       lowerCamelCase__	:     List[str]								=		TFMobileViTForSemanticSegmentation(lowerCamelCase_   )
       lowerCamelCase__	:     int								=		self.image_size // self.output_stride

       lowerCamelCase__	:     Optional[Any]								=		model(lowerCamelCase_,	training=lowerCamelCase_   )
       self.parent.assertEqual(
           result.logits.shape,	(self.batch_size, self.num_labels, expected_height, expected_width)   )

       lowerCamelCase__	:     str								=		model(lowerCamelCase_,	labels=lowerCamelCase_,	training=lowerCamelCase_   )
       self.parent.assertEqual(
           result.logits.shape,	(self.batch_size, self.num_labels, expected_height, expected_width)   )





      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		self.prepare_config_and_inputs()
       lowerCamelCase__							,	lowerCamelCase__							,	lowerCamelCase__							,	lowerCamelCase__	:     str								=		config_and_inputs
       lowerCamelCase__	:     Union[str, Any]								=		{'pixel_values': pixel_values}
       return config, inputs_dict



@require_tf
class 						a_ (      snake_case_    ,		snake_case_    ,		unittest.TestCase					):







      '''simple docstring'''

      lowerCamelCase__			:							str					=      (
          (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
          if is_tf_available()
          else ()
      )
      lowerCamelCase__			:							Union[str, Any]					=      (
          {'feature-extraction': TFMobileViTModel, 'image-classification': TFMobileViTForImageClassification}
          if is_tf_available()
          else {}
      )

      lowerCamelCase__			:							List[Any]					=      False
      lowerCamelCase__			:							Any					=      False
      lowerCamelCase__			:							int					=      False
      lowerCamelCase__			:							Optional[int]					=      False
      lowerCamelCase__			:							str					=      False




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		TFMobileViTModelTester(self   )
       lowerCamelCase__	:     int								=		TFMobileViTConfigTester(self,	config_class=lowerCamelCase_,	has_text_modality=lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       self.config_tester.run_common_tests()




      @unittest.skip(reason='MobileViT does not use inputs_embeds'   )
      def      a__				(self   ):

       '''simple docstring'''



       pass




      @unittest.skip(reason='MobileViT does not support input and output embeddings'   )
      def      a__				(self   ):

       '''simple docstring'''



       pass




      @unittest.skip(reason='MobileViT does not output attentions'   )
      def      a__				(self   ):

       '''simple docstring'''



       pass




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__							,	lowerCamelCase__	:     Optional[Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase__	:     List[str]								=		model_class(lowerCamelCase_   )
        lowerCamelCase__	:     List[str]								=		inspect.signature(model.call   )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        lowerCamelCase__	:     List[Any]								=		[*signature.parameters.keys()]

        lowerCamelCase__	:     List[str]								=		['pixel_values']
        self.assertListEqual(arg_names[:1],	lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     int								=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       def check_hidden_states_output(lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):
        lowerCamelCase__	:     Tuple								=		model_class(lowerCamelCase_   )

        lowerCamelCase__	:     Union[str, Any]								=		model(**self._prepare_for_class(lowerCamelCase_,	lowerCamelCase_   )   )

        lowerCamelCase__	:     Optional[int]								=		outputs.hidden_states

        lowerCamelCase__	:     str								=		5
        self.assertEqual(len(lowerCamelCase_   ),	lowerCamelCase_   )

        # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
        # with the width and height being successively divided by 2.
        lowerCamelCase__	:     Dict								=		2
        for i in range(len(lowerCamelCase_   )   ):
         self.assertListEqual(
             list(hidden_states[i].shape[-2:]   ),	[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor],	)
         divisor *= 2

        self.assertEqual(self.model_tester.output_stride,	divisor // 2   )

       lowerCamelCase__							,	lowerCamelCase__	:     Optional[int]								=		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase__	:     Union[str, Any]								=		True
        check_hidden_states_output(lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowerCamelCase__	:     Optional[Any]								=		True

        check_hidden_states_output(lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[Any]								=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase_   )




      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0,	reason='TF does not support backprop for grouped convolutions on CPU.',	)
      def      a__				(self   ):

       '''simple docstring'''



       super().test_dataset_conversion()




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_=2e-1,	lowerCamelCase_=2e-1   ):

       '''simple docstring'''



       self.assertTrue(np.allclose(lowerCamelCase_,	lowerCamelCase_,	atol=lowerCamelCase_,	rtol=lowerCamelCase_   )   )




      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0,	reason='TF does not support backprop for grouped convolutions on CPU.',	)
      @slow
      def      a__				(self   ):

       '''simple docstring'''



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

       for model_class in self.all_model_classes:
        # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
        if model_class.__name__ != "TFMobileViTModel":
         lowerCamelCase__	:     Optional[Any]								=		model_class(lowerCamelCase_   )
         if getattr(lowerCamelCase_,	'hf_compute_loss',	lowerCamelCase_   ):
          super().test_keras_fit()




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__							,	lowerCamelCase__	:     List[Any]								=		self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes:
        # set an ignore index to correctly test the masked loss used in
        # `TFMobileViTForSemanticSegmentation`.
        if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
         lowerCamelCase__	:     Any								=		5

        lowerCamelCase__	:     List[str]								=		model_class(lowerCamelCase_   )
        if getattr(lowerCamelCase_,	'hf_compute_loss',	lowerCamelCase_   ):
         # The number of elements in the loss should be the same as the number of elements in the label
         lowerCamelCase__	:     str								=		self._prepare_for_class(inputs_dict.copy(),	lowerCamelCase_,	return_labels=lowerCamelCase_   )
         lowerCamelCase__	:     List[str]								=		prepared_for_class[
             sorted(prepared_for_class.keys() - inputs_dict.keys(),	reverse=lowerCamelCase_   )[0]
         ]
         lowerCamelCase__	:     Optional[int]								=		added_label.shape.as_list()[:1]

         # Test that model correctly compute the loss with kwargs
         lowerCamelCase__	:     str								=		self._prepare_for_class(inputs_dict.copy(),	lowerCamelCase_,	return_labels=lowerCamelCase_   )
         lowerCamelCase__	:     Dict								=		{'input_ids', 'pixel_values', 'input_features'}
         lowerCamelCase__	:     List[str]								=		possible_input_names.intersection(set(lowerCamelCase_   )   ).pop()
         lowerCamelCase__	:     int								=		prepared_for_class.pop(lowerCamelCase_   )

         lowerCamelCase__	:     Optional[Any]								=		model(lowerCamelCase_,	**lowerCamelCase_   )[0]
         self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

         # Test that model correctly compute the loss when we mask some positions
         lowerCamelCase__	:     Dict								=		self._prepare_for_class(inputs_dict.copy(),	lowerCamelCase_,	return_labels=lowerCamelCase_   )
         lowerCamelCase__	:     List[str]								=		{'input_ids', 'pixel_values', 'input_features'}
         lowerCamelCase__	:     Dict								=		possible_input_names.intersection(set(lowerCamelCase_   )   ).pop()
         lowerCamelCase__	:     int								=		prepared_for_class.pop(lowerCamelCase_   )
         if "labels" in prepared_for_class:
          lowerCamelCase__	:     Any								=		prepared_for_class['labels'].numpy()
          if len(labels.shape   ) > 1 and labels.shape[1] != 1:
           # labels[0] = -100
           lowerCamelCase__	:     Any								=		tf.convert_to_tensor(lowerCamelCase_   )
           lowerCamelCase__	:     Tuple								=		model(lowerCamelCase_,	**lowerCamelCase_   )[0]
           self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )
           self.assertTrue(not np.any(np.isnan(loss.numpy()   )   )   )

                # Test that model correctly compute the loss with a dict
         lowerCamelCase__	:     int								=		self._prepare_for_class(inputs_dict.copy(),	lowerCamelCase_,	return_labels=lowerCamelCase_   )
         lowerCamelCase__	:     int								=		model(lowerCamelCase_   )[0]
         self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

         # Test that model correctly compute the loss with a tuple
         lowerCamelCase__	:     List[str]								=		self._prepare_for_class(inputs_dict.copy(),	lowerCamelCase_,	return_labels=lowerCamelCase_   )

         # Get keys that were added with the _prepare_for_class function
         lowerCamelCase__	:     str								=		prepared_for_class.keys() - inputs_dict.keys()
         lowerCamelCase__	:     List[str]								=		inspect.signature(model.call   ).parameters
         lowerCamelCase__	:     List[str]								=		list(signature.keys()   )

         # Create a dictionary holding the location of the tensors in the tuple
         lowerCamelCase__	:     Dict								=		{0: input_name}
         for label_key in label_keys:
          lowerCamelCase__	:     List[Any]								=		signature_names.index(lowerCamelCase_   )
          lowerCamelCase__	:     Tuple								=		label_key
         lowerCamelCase__	:     Optional[Any]								=		sorted(tuple_index_mapping.items()   )
         # Initialize a list with their default values, update the values and convert to a tuple
         lowerCamelCase__	:     Tuple								=		[]

         for name in signature_names:
          if name != "kwargs":
           list_input.append(signature[name].default   )

         for index, value in sorted_tuple_index_mapping:
          lowerCamelCase__	:     Union[str, Any]								=		prepared_for_class[value]

         lowerCamelCase__	:     str								=		tuple(lowerCamelCase_   )

         # Send to model
         lowerCamelCase__	:     Optional[int]								=		model(tuple_input[:-1]   )[0]

         self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )





      @slow
      def      a__				(self   ):

       '''simple docstring'''



       for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase__	:     Union[str, Any]								=		TFMobileViTModel.from_pretrained(lowerCamelCase_   )
        self.assertIsNotNone(lowerCamelCase_   )






def 			lowerCamelCase_    (		):
 lowerCamelCase__	:     Tuple								=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
 return image





@require_tf
class 						a_ (      unittest.TestCase					):







      '''simple docstring'''

      @slow
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'   )

       lowerCamelCase__	:     List[str]								=		MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'   )
       lowerCamelCase__	:     Dict								=		prepare_img()
       lowerCamelCase__	:     Any								=		image_processor(images=lowerCamelCase_,	return_tensors='tf'   )

       # forward pass
       lowerCamelCase__	:     Optional[Any]								=		model(**lowerCamelCase_,	training=lowerCamelCase_   )

       # verify the logits
       lowerCamelCase__	:     List[str]								=		tf.TensorShape((1, 1_0_0_0)   )
       self.assertEqual(outputs.logits.shape,	lowerCamelCase_   )

       lowerCamelCase__	:     List[Any]								=		tf.constant([-1.9_364, -1.2_327, -0.4_653]   )

       tf.debugging.assert_near(outputs.logits[0, :3],	lowerCamelCase_,	atol=1e-4,	rtol=1e-04   )





      @slow
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'   )

       lowerCamelCase__	:     Union[str, Any]								=		MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'   )

       lowerCamelCase__	:     str								=		prepare_img()
       lowerCamelCase__	:     int								=		image_processor(images=lowerCamelCase_,	return_tensors='tf'   )

       # forward pass
       lowerCamelCase__	:     Optional[int]								=		model(inputs.pixel_values,	training=lowerCamelCase_   )
       lowerCamelCase__	:     List[Any]								=		outputs.logits

       # verify the logits
       lowerCamelCase__	:     Any								=		tf.TensorShape((1, 2_1, 3_2, 3_2)   )
       self.assertEqual(logits.shape,	lowerCamelCase_   )

       lowerCamelCase__	:     Any								=		tf.constant(
           [
               [[6.9_713, 6.9_786, 7.2_422], [7.2_893, 7.2_825, 7.4_446], [7.6_580, 7.8_797, 7.9_420]],
               [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
               [[-3.3_089, -2.8_539, -2.6_740], [-3.2_706, -2.5_621, -2.5_108], [-3.2_534, -2.6_615, -2.6_651]],
           ]   )

       tf.debugging.assert_near(logits[0, :3, :3, :3],	lowerCamelCase_,	rtol=1e-4,	atol=1e-4   )









"""simple docstring"""
import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class 						a_ (      snake_case_    ,		unittest.TestCase					):







      '''simple docstring'''

      lowerCamelCase__			:							Optional[Any]					=      KandinskyPriorPipeline
      lowerCamelCase__			:							Any					=      ['prompt']
      lowerCamelCase__			:							Any					=      ['prompt', 'negative_prompt']
      lowerCamelCase__			:							str					=      [
          'num_images_per_prompt',
          'generator',
          'num_inference_steps',
          'latents',
          'negative_prompt',
          'guidance_scale',
          'output_type',
          'return_dict',
      ]
      lowerCamelCase__			:							Dict					=      False




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 3_2




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 3_2




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return self.time_input_dim




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return self.time_input_dim * 4




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 1_0_0




      @property
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Any								=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )
       return tokenizer




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )
       lowerCamelCase__	:     int								=		CLIPTextConfig(
           bos_token_id=0,	eos_token_id=2,	hidden_size=self.text_embedder_hidden_size,	projection_dim=self.text_embedder_hidden_size,	intermediate_size=3_7,	layer_norm_eps=1e-05,	num_attention_heads=4,	num_hidden_layers=5,	pad_token_id=1,	vocab_size=1_0_0_0,	)
       return CLIPTextModelWithProjection(lowerCamelCase_   )




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )

       lowerCamelCase__	:     Optional[int]								=		{
           'num_attention_heads': 2,
           'attention_head_dim': 1_2,
           'embedding_dim': self.text_embedder_hidden_size,
           'num_layers': 1,
       }

       lowerCamelCase__	:     Optional[int]								=		PriorTransformer(**lowerCamelCase_   )
       # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
       lowerCamelCase__	:     Dict								=		nn.Parameter(torch.ones(model.clip_std.shape   )   )
       return model




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )
       lowerCamelCase__	:     List[str]								=		CLIPVisionConfig(
           hidden_size=self.text_embedder_hidden_size,	image_size=2_2_4,	projection_dim=self.text_embedder_hidden_size,	intermediate_size=3_7,	num_attention_heads=4,	num_channels=3,	num_hidden_layers=5,	patch_size=1_4,	)

       lowerCamelCase__	:     int								=		CLIPVisionModelWithProjection(lowerCamelCase_   )
       return model




      @property
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		CLIPImageProcessor(
           crop_size=2_2_4,	do_center_crop=lowerCamelCase_,	do_normalize=lowerCamelCase_,	do_resize=lowerCamelCase_,	image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073],	image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711],	resample=3,	size=2_2_4,	)

       return image_processor




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		self.dummy_prior
       lowerCamelCase__	:     Optional[Any]								=		self.dummy_image_encoder
       lowerCamelCase__	:     Optional[Any]								=		self.dummy_text_encoder
       lowerCamelCase__	:     Union[str, Any]								=		self.dummy_tokenizer
       lowerCamelCase__	:     List[Any]								=		self.dummy_image_processor

       lowerCamelCase__	:     List[Any]								=		UnCLIPScheduler(
           variance_type='fixed_small_log',	prediction_type='sample',	num_train_timesteps=1_0_0_0,	clip_sample=lowerCamelCase_,	clip_sample_range=10.0,	)

       lowerCamelCase__	:     Union[str, Any]								=		{
           'prior': prior,
           'image_encoder': image_encoder,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'scheduler': scheduler,
           'image_processor': image_processor,
       }

       return components




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_=0   ):

       '''simple docstring'''



       if str(lowerCamelCase_   ).startswith('mps'   ):
        lowerCamelCase__	:     List[Any]								=		torch.manual_seed(lowerCamelCase_   )
       else:
        lowerCamelCase__	:     Optional[int]								=		torch.Generator(device=lowerCamelCase_   ).manual_seed(lowerCamelCase_   )
       lowerCamelCase__	:     List[Any]								=		{
           'prompt': 'horse',
           'generator': generator,
           'guidance_scale': 4.0,
           'num_inference_steps': 2,
           'output_type': 'np',
       }
       return inputs




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		'cpu'

       lowerCamelCase__	:     str								=		self.get_dummy_components()

       lowerCamelCase__	:     Any								=		self.pipeline_class(**lowerCamelCase_   )
       lowerCamelCase__	:     Dict								=		pipe.to(lowerCamelCase_   )

       pipe.set_progress_bar_config(disable=lowerCamelCase_   )

       lowerCamelCase__	:     Tuple								=		pipe(**self.get_dummy_inputs(lowerCamelCase_   )   )
       lowerCamelCase__	:     Dict								=		output.image_embeds

       lowerCamelCase__	:     Optional[Any]								=		pipe(
           **self.get_dummy_inputs(lowerCamelCase_   ),	return_dict=lowerCamelCase_,	)[0]

       lowerCamelCase__	:     Dict								=		image[0, -1_0:]
       lowerCamelCase__	:     Tuple								=		image_from_tuple[0, -1_0:]

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

       lowerCamelCase__	:     Dict								=		np.array(
           [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2
       assert np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1e-2




      @skip_mps
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		torch_device == 'cpu'
       lowerCamelCase__	:     Any								=		True
       lowerCamelCase__	:     List[Any]								=		False

       self._test_inference_batch_single_identical(
           test_max_difference=lowerCamelCase_,	relax_max_difference=lowerCamelCase_,	test_mean_pixel_difference=lowerCamelCase_,	)





      @skip_mps
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		torch_device == 'cpu'
       lowerCamelCase__	:     int								=		False

       self._test_attention_slicing_forward_pass(
           test_max_difference=lowerCamelCase_,	test_mean_pixel_difference=lowerCamelCase_,	)

