





import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


_UpperCAmelCase             =							False






class        snake_case_    (		unittest.TestCase						):
		pass






@nightly
@require_torch_gpu
class        snake_case_    (		unittest.TestCase						):






		def 				UpperCAmelCase__						(							self			:					Optional[Any]      )->Tuple:






			'''simple docstring'''

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






		def 				UpperCAmelCase__						(							self			:					Any      )->Optional[Any]:






			'''simple docstring'''

			__lowerCAmelCase					:	str      =       VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion"""       ,  torch_dtype=torch.floataa      )
			pipe.to(UpperCamelCase__      )
			pipe.set_progress_bar_config(disable=UpperCamelCase__      )

			__lowerCAmelCase					:	Any      =       load_image(
			    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""      )

			__lowerCAmelCase					:	Optional[int]      =       torch.manual_seed(0      )
			__lowerCAmelCase					:	Optional[Any]      =       pipe.dual_guided(
			    prompt="""first prompt"""       ,  image=UpperCamelCase__       ,  text_to_image_strength=0.75       ,  generator=UpperCamelCase__       ,  guidance_scale=7.5       ,  num_inference_steps=2       ,  output_type="""numpy"""       ,  ).images

			with tempfile.TemporaryDirectory() as tmpdirname:
				pipe.save_pretrained(UpperCamelCase__      )
				__lowerCAmelCase					:	List[Any]      =       VersatileDiffusionPipeline.from_pretrained(UpperCamelCase__       ,  torch_dtype=torch.floataa      )
			pipe.to(UpperCamelCase__      )
			pipe.set_progress_bar_config(disable=UpperCamelCase__      )

			__lowerCAmelCase					:	Any      =       generator.manual_seed(0      )
			__lowerCAmelCase					:	Dict      =       pipe.dual_guided(
			    prompt="""first prompt"""       ,  image=UpperCamelCase__       ,  text_to_image_strength=0.75       ,  generator=UpperCamelCase__       ,  guidance_scale=7.5       ,  num_inference_steps=2       ,  output_type="""numpy"""       ,  ).images

			assert np.abs(image - new_image      ).sum() < 1E-5, "Models don't have the same forward pass"






		def 				UpperCAmelCase__						(							self			:					Dict      )->str:






			'''simple docstring'''

			__lowerCAmelCase					:	List[str]      =       VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion"""       ,  torch_dtype=torch.floataa      )
			pipe.to(UpperCamelCase__      )
			pipe.set_progress_bar_config(disable=UpperCamelCase__      )

			__lowerCAmelCase					:	Optional[Any]      =       "cyberpunk 2077"
			__lowerCAmelCase					:	Any      =       load_image(
			    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""      )
			__lowerCAmelCase					:	List[str]      =       torch.manual_seed(0      )
			__lowerCAmelCase					:	Optional[Any]      =       pipe.dual_guided(
			    prompt=UpperCamelCase__       ,  image=UpperCamelCase__       ,  text_to_image_strength=0.75       ,  generator=UpperCamelCase__       ,  guidance_scale=7.5       ,  num_inference_steps=50       ,  output_type="""numpy"""       ,  ).images

			__lowerCAmelCase					:	Union[str, Any]      =       image[0, 253:256, 253:256, -1]

			assert image.shape == (1, 512, 512, 3)
			__lowerCAmelCase					:	Any      =       np.array([0.1_448, 0.1_619, 0.1_741, 0.1_086, 0.1_147, 0.1_128, 0.1_199, 0.1_165, 0.1_001]      )

			assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-1

			__lowerCAmelCase					:	Optional[Any]      =       "A painting of a squirrel eating a burger "
			__lowerCAmelCase					:	Optional[Any]      =       torch.manual_seed(0      )
			__lowerCAmelCase					:	Tuple      =       pipe.text_to_image(
			    prompt=UpperCamelCase__       ,  generator=UpperCamelCase__       ,  guidance_scale=7.5       ,  num_inference_steps=50       ,  output_type="""numpy"""      ).images

			__lowerCAmelCase					:	Tuple      =       image[0, 253:256, 253:256, -1]

			assert image.shape == (1, 512, 512, 3)
			__lowerCAmelCase					:	str      =       np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778]      )

			assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-1

			__lowerCAmelCase					:	Union[str, Any]      =       pipe.image_variation(UpperCamelCase__       ,  generator=UpperCamelCase__       ,  output_type="""numpy"""      ).images

			__lowerCAmelCase					:	Optional[Any]      =       image[0, 253:256, 253:256, -1]

			assert image.shape == (1, 512, 512, 3)
			__lowerCAmelCase					:	Optional[Any]      =       np.array([0.3_076, 0.3_123, 0.3_284, 0.3_782, 0.3_770, 0.3_894, 0.4_297, 0.4_331, 0.4_456]      )

			assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-1






import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
      import jax

      from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel






class        snake_case_    (		unittest.TestCase						):






  def __init__(							self			:					List[Any]       ,  _snake_case			:					List[Any]       ,  _snake_case			:					str=13       ,  _snake_case			:					int=30       ,  _snake_case			:					str=2       ,  _snake_case			:					int=3       ,  _snake_case			:					Optional[Any]=True       ,  _snake_case			:					str=True       ,  _snake_case			:					Optional[int]=32       ,  _snake_case			:					Dict=5       ,  _snake_case			:					Optional[int]=4       ,  _snake_case			:					List[Any]=37       ,  _snake_case			:					Union[str, Any]="gelu"       ,  _snake_case			:					str=0.1       ,  _snake_case			:					str=0.1       ,  _snake_case			:					str=10       ,  _snake_case			:					Any=0.02       ,  )->Tuple:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[int]      =       parent
   __lowerCAmelCase					:	Any      =       batch_size
   __lowerCAmelCase					:	int      =       image_size
   __lowerCAmelCase					:	int      =       patch_size
   __lowerCAmelCase					:	List[Any]      =       num_channels
   __lowerCAmelCase					:	str      =       is_training
   __lowerCAmelCase					:	str      =       use_labels
   __lowerCAmelCase					:	List[str]      =       hidden_size
   __lowerCAmelCase					:	Dict      =       num_hidden_layers
   __lowerCAmelCase					:	List[str]      =       num_attention_heads
   __lowerCAmelCase					:	Any      =       intermediate_size
   __lowerCAmelCase					:	List[str]      =       hidden_act
   __lowerCAmelCase					:	List[str]      =       hidden_dropout_prob
   __lowerCAmelCase					:	Any      =       attention_probs_dropout_prob
   __lowerCAmelCase					:	Tuple      =       type_sequence_label_size
   __lowerCAmelCase					:	Union[str, Any]      =       initializer_range

   # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
   __lowerCAmelCase					:	Tuple      =       (image_size // patch_size) ** 2
   __lowerCAmelCase					:	Optional[Any]      =       num_patches + 1






  def 				UpperCAmelCase__						(							self			:					Any      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

   __lowerCAmelCase					:	Tuple      =       ViTConfig(
       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       ,  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=_snake_case       ,  initializer_range=self.initializer_range       ,  )

   return config, pixel_values






  def 				UpperCAmelCase__						(							self			:					List[Any]       ,  _snake_case			:					List[str]       ,  _snake_case			:					List[Any]      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       FlaxViTModel(config=_snake_case      )
   __lowerCAmelCase					:	int      =       model(_snake_case      )
   # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
   __lowerCAmelCase					:	Dict      =       (self.image_size, self.image_size)
   __lowerCAmelCase					:	Any      =       (self.patch_size, self.patch_size)
   __lowerCAmelCase					:	Any      =       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
   self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, num_patches + 1, self.hidden_size)      )






  def 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					str       ,  _snake_case			:					List[Any]      )->Union[str, Any]:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       self.type_sequence_label_size
   __lowerCAmelCase					:	Tuple      =       FlaxViTForImageClassification(config=_snake_case      )
   __lowerCAmelCase					:	List[str]      =       model(_snake_case      )
   self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.type_sequence_label_size)      )

   # test greyscale images
   __lowerCAmelCase					:	str      =       1
   __lowerCAmelCase					:	Any      =       FlaxViTForImageClassification(_snake_case      )

   __lowerCAmelCase					:	int      =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
   __lowerCAmelCase					:	Dict      =       model(_snake_case      )






  def 				UpperCAmelCase__						(							self			:					str      )->Any:






   '''simple docstring'''

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






@require_flax
class        snake_case_    (		__lowercase					,unittest.TestCase						):
  A_      							=   (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()






  def 				UpperCAmelCase__						(							self			:					str      )->None:






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       FlaxViTModelTester(self      )
   __lowerCAmelCase					:	Optional[Any]      =       ConfigTester(self       ,  config_class=_snake_case       ,  has_text_modality=_snake_case       ,  hidden_size=37      )






  def 				UpperCAmelCase__						(							self			:					Any      )->Dict:






   '''simple docstring'''

   self.config_tester.run_common_tests()






  def 				UpperCAmelCase__						(							self			:					Any      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	Dict      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_snake_case      )






  def 				UpperCAmelCase__						(							self			:					Union[str, Any]      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Dict      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*_snake_case      )






  def 				UpperCAmelCase__						(							self			:					int      )->int:






   '''simple docstring'''

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

   for model_class in self.all_model_classes:
    __lowerCAmelCase					:	int      =       model_class(_snake_case      )
    __lowerCAmelCase					:	Optional[int]      =       inspect.signature(model.__call__      )
    # signature.parameters is an OrderedDict => so arg_names order is deterministic
    __lowerCAmelCase					:	Tuple      =       [*signature.parameters.keys()]

    __lowerCAmelCase					:	str      =       ["""pixel_values"""]
    self.assertListEqual(arg_names[:1]       ,  _snake_case      )






  def 				UpperCAmelCase__						(							self			:					str      )->str:






   '''simple docstring'''

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

   for model_class in self.all_model_classes:
    with self.subTest(model_class.__name__      ):
     __lowerCAmelCase					:	Optional[int]      =       self._prepare_for_class(_snake_case       ,  _snake_case      )
     __lowerCAmelCase					:	List[str]      =       model_class(_snake_case      )

     @jax.jit
     def model_jitted(_snake_case			:					Dict       ,  **_snake_case			:					Union[str, Any]      ):
      return model(pixel_values=_snake_case       ,  **_snake_case      )

     with self.subTest("""JIT Enabled"""      ):
      __lowerCAmelCase					:	List[Any]      =       model_jitted(**_snake_case      ).to_tuple()

     with self.subTest("""JIT Disabled"""      ):
      with jax.disable_jit():
       __lowerCAmelCase					:	str      =       model_jitted(**_snake_case      ).to_tuple()

     self.assertEqual(len(_snake_case      )       ,  len(_snake_case      )      )
     for jitted_output, output in zip(_snake_case       ,  _snake_case      ):
      self.assertEqual(jitted_output.shape       ,  output.shape      )






  @slow
  def 				UpperCAmelCase__						(							self			:					Dict      )->str:






   '''simple docstring'''

   for model_class_name in self.all_model_classes:
    __lowerCAmelCase					:	List[str]      =       model_class_name.from_pretrained("""google/vit-base-patch16-224"""      )
    __lowerCAmelCase					:	List[str]      =       model(np.ones((1, 3, 224, 224)      )      )
    self.assertIsNotNone(_snake_case      )