





import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class        snake_case_    (		__lowercase					,__lowercase					,unittest.TestCase						):
  A_      							=   StableDiffusionDiffEditPipeline
  A_      							=   TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'}
  A_      							=   TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'}
  A_      							=   frozenset(
      []						)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
  A_      							=   frozenset([]						)






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






   '''simple docstring'''

   torch.manual_seed(0      )
   __lowerCAmelCase					:	Tuple      =       UNetaDConditionModel(
       block_out_channels=(32, 64)       ,  layers_per_block=2       ,  sample_size=32       ,  in_channels=4       ,  out_channels=4       ,  down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")       ,  up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")       ,  cross_attention_dim=32       ,  attention_head_dim=(2, 4)       ,  use_linear_projection=_snake_case       ,  )
   __lowerCAmelCase					:	List[Any]      =       DDIMScheduler(
       beta_start=0.00_085       ,  beta_end=0.012       ,  beta_schedule="""scaled_linear"""       ,  clip_sample=_snake_case       ,  set_alpha_to_one=_snake_case       ,  )
   __lowerCAmelCase					:	Optional[int]      =       DDIMInverseScheduler(
       beta_start=0.00_085       ,  beta_end=0.012       ,  beta_schedule="""scaled_linear"""       ,  clip_sample=_snake_case       ,  set_alpha_to_zero=_snake_case       ,  )
   torch.manual_seed(0      )
   __lowerCAmelCase					:	str      =       AutoencoderKL(
       block_out_channels=[32, 64]       ,  in_channels=3       ,  out_channels=3       ,  down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]       ,  up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]       ,  latent_channels=4       ,  sample_size=128       ,  )
   torch.manual_seed(0      )
   __lowerCAmelCase					:	Optional[Any]      =       CLIPTextConfig(
       bos_token_id=0       ,  eos_token_id=2       ,  hidden_size=32       ,  intermediate_size=37       ,  layer_norm_eps=1E-05       ,  num_attention_heads=4       ,  num_hidden_layers=5       ,  pad_token_id=1       ,  vocab_size=1000       ,  hidden_act="""gelu"""       ,  projection_dim=512       ,  )
   __lowerCAmelCase					:	Optional[int]      =       CLIPTextModel(_snake_case      )
   __lowerCAmelCase					:	List[str]      =       CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""      )

   __lowerCAmelCase					:	Optional[int]      =       {
       """unet""": unet,
       """scheduler""": scheduler,
       """inverse_scheduler""": inverse_scheduler,
       """vae""": vae,
       """text_encoder""": text_encoder,
       """tokenizer""": tokenizer,
       """safety_checker""": None,
       """feature_extractor""": None,
   }

   return components






  def 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					List[str]       ,  _snake_case			:					Optional[int]=0      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       floats_tensor((1, 16, 16)       ,  rng=random.Random(_snake_case      )      ).to(_snake_case      )
   __lowerCAmelCase					:	Dict      =       floats_tensor((1, 2, 4, 16, 16)       ,  rng=random.Random(_snake_case      )      ).to(_snake_case      )
   if str(_snake_case      ).startswith("""mps"""      ):
    __lowerCAmelCase					:	Tuple      =       torch.manual_seed(_snake_case      )
   else:
    __lowerCAmelCase					:	Any      =       torch.Generator(device=_snake_case      ).manual_seed(_snake_case      )
   __lowerCAmelCase					:	List[str]      =       {
       """prompt""": """a dog and a newt""",
       """mask_image""": mask,
       """image_latents""": latents,
       """generator""": generator,
       """num_inference_steps""": 2,
       """inpaint_strength""": 1.0,
       """guidance_scale""": 6.0,
       """output_type""": """numpy""",
   }

   return inputs






  def 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					Optional[int]       ,  _snake_case			:					Any=0      )->List[str]:






   '''simple docstring'''

   __lowerCAmelCase					:	Union[str, Any]      =       floats_tensor((1, 3, 32, 32)       ,  rng=random.Random(_snake_case      )      ).to(_snake_case      )
   __lowerCAmelCase					:	Union[str, Any]      =       image.cpu().permute(0       ,  2       ,  3       ,  1      )[0]
   __lowerCAmelCase					:	str      =       Image.fromarray(np.uinta(_snake_case      )      ).convert("""RGB"""      )
   if str(_snake_case      ).startswith("""mps"""      ):
    __lowerCAmelCase					:	Tuple      =       torch.manual_seed(_snake_case      )
   else:
    __lowerCAmelCase					:	int      =       torch.Generator(device=_snake_case      ).manual_seed(_snake_case      )
   __lowerCAmelCase					:	str      =       {
       """image""": image,
       """source_prompt""": """a cat and a frog""",
       """target_prompt""": """a dog and a newt""",
       """generator""": generator,
       """num_inference_steps""": 2,
       """num_maps_per_mask""": 2,
       """mask_encode_strength""": 1.0,
       """guidance_scale""": 6.0,
       """output_type""": """numpy""",
   }

   return inputs






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






   '''simple docstring'''

   __lowerCAmelCase					:	int      =       floats_tensor((1, 3, 32, 32)       ,  rng=random.Random(_snake_case      )      ).to(_snake_case      )
   __lowerCAmelCase					:	List[str]      =       image.cpu().permute(0       ,  2       ,  3       ,  1      )[0]
   __lowerCAmelCase					:	List[Any]      =       Image.fromarray(np.uinta(_snake_case      )      ).convert("""RGB"""      )
   if str(_snake_case      ).startswith("""mps"""      ):
    __lowerCAmelCase					:	List[Any]      =       torch.manual_seed(_snake_case      )
   else:
    __lowerCAmelCase					:	Union[str, Any]      =       torch.Generator(device=_snake_case      ).manual_seed(_snake_case      )
   __lowerCAmelCase					:	Tuple      =       {
       """image""": image,
       """prompt""": """a cat and a frog""",
       """generator""": generator,
       """num_inference_steps""": 2,
       """inpaint_strength""": 1.0,
       """guidance_scale""": 6.0,
       """decode_latents""": True,
       """output_type""": """numpy""",
   }
   return inputs






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






   '''simple docstring'''

   if not hasattr(self.pipeline_class       ,  """_optional_components"""      ):
    return

   __lowerCAmelCase					:	Optional[int]      =       self.get_dummy_components()
   __lowerCAmelCase					:	Tuple      =       self.pipeline_class(**_snake_case      )
   pipe.to(_snake_case      )
   pipe.set_progress_bar_config(disable=_snake_case      )

   # set all optional components to None and update pipeline config accordingly
   for optional_component in pipe._optional_components:
    setattr(_snake_case       ,  _snake_case       ,  _snake_case      )
   pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}      )

   __lowerCAmelCase					:	Tuple      =       self.get_dummy_inputs(_snake_case      )
   __lowerCAmelCase					:	Union[str, Any]      =       pipe(**_snake_case      )[0]

   with tempfile.TemporaryDirectory() as tmpdir:
    pipe.save_pretrained(_snake_case      )
    __lowerCAmelCase					:	Dict      =       self.pipeline_class.from_pretrained(_snake_case      )
    pipe_loaded.to(_snake_case      )
    pipe_loaded.set_progress_bar_config(disable=_snake_case      )

   for optional_component in pipe._optional_components:
    self.assertTrue(
        getattr(_snake_case       ,  _snake_case      ) is None       ,  F'''`{optional_component}` did not stay set to None after loading.'''       ,  )

   __lowerCAmelCase					:	Optional[Any]      =       self.get_dummy_inputs(_snake_case      )
   __lowerCAmelCase					:	Tuple      =       pipe_loaded(**_snake_case      )[0]

   __lowerCAmelCase					:	Dict      =       np.abs(output - output_loaded      ).max()
   self.assertLess(_snake_case       ,  1E-4      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[int]      =       """cpu"""

   __lowerCAmelCase					:	int      =       self.get_dummy_components()
   __lowerCAmelCase					:	List[str]      =       self.pipeline_class(**_snake_case      )
   pipe.to(_snake_case      )
   pipe.set_progress_bar_config(disable=_snake_case      )

   __lowerCAmelCase					:	List[str]      =       self.get_dummy_mask_inputs(_snake_case      )
   __lowerCAmelCase					:	Tuple      =       pipe.generate_mask(**_snake_case      )
   __lowerCAmelCase					:	Union[str, Any]      =       mask[0, -3:, -3:]

   self.assertEqual(mask.shape       ,  (1, 16, 16)      )
   __lowerCAmelCase					:	List[Any]      =       np.array([0] * 9      )
   __lowerCAmelCase					:	Optional[Any]      =       np.abs(mask_slice.flatten() - expected_slice      ).max()
   self.assertLessEqual(_snake_case       ,  1E-3      )
   self.assertEqual(mask[0, -3, -4]       ,  0      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       """cpu"""

   __lowerCAmelCase					:	List[str]      =       self.get_dummy_components()
   __lowerCAmelCase					:	Any      =       self.pipeline_class(**_snake_case      )
   pipe.to(_snake_case      )
   pipe.set_progress_bar_config(disable=_snake_case      )

   __lowerCAmelCase					:	Optional[Any]      =       self.get_dummy_inversion_inputs(_snake_case      )
   __lowerCAmelCase					:	str      =       pipe.invert(**_snake_case      ).images
   __lowerCAmelCase					:	Tuple      =       image[0, -1, -3:, -3:]

   self.assertEqual(image.shape       ,  (2, 32, 32, 3)      )
   __lowerCAmelCase					:	List[Any]      =       np.array(
       [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799]       ,  )
   __lowerCAmelCase					:	List[Any]      =       np.abs(image_slice.flatten() - expected_slice      ).max()
   self.assertLessEqual(_snake_case       ,  1E-3      )






  def 				UpperCAmelCase__						(							self			:					Dict      )->Dict:






   '''simple docstring'''

   super().test_inference_batch_single_identical(expected_max_diff=5E-3      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       """cpu"""

   __lowerCAmelCase					:	int      =       self.get_dummy_components()

   __lowerCAmelCase					:	Union[str, Any]      =       {"""beta_start""": 0.00_085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""}
   __lowerCAmelCase					:	Optional[int]      =       DPMSolverMultistepScheduler(**_snake_case      )
   __lowerCAmelCase					:	str      =       DPMSolverMultistepInverseScheduler(**_snake_case      )

   __lowerCAmelCase					:	Tuple      =       self.pipeline_class(**_snake_case      )
   pipe.to(_snake_case      )
   pipe.set_progress_bar_config(disable=_snake_case      )

   __lowerCAmelCase					:	Any      =       self.get_dummy_inversion_inputs(_snake_case      )
   __lowerCAmelCase					:	Dict      =       pipe.invert(**_snake_case      ).images
   __lowerCAmelCase					:	Dict      =       image[0, -1, -3:, -3:]

   self.assertEqual(image.shape       ,  (2, 32, 32, 3)      )
   __lowerCAmelCase					:	Dict      =       np.array(
       [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799]       ,  )
   __lowerCAmelCase					:	Union[str, Any]      =       np.abs(image_slice.flatten() - expected_slice      ).max()
   self.assertLessEqual(_snake_case       ,  1E-3      )






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






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






   '''simple docstring'''

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






  @classmethod
  def 				UpperCAmelCase__						(							cls			:					Optional[int]      )->List[str]:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[int]      =       load_image(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"""      )

   __lowerCAmelCase					:	Dict      =       raw_image.convert("""RGB"""      ).resize((768, 768)      )

   __lowerCAmelCase					:	Dict      =       raw_image






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






   '''simple docstring'''

   __lowerCAmelCase					:	Union[str, Any]      =       torch.manual_seed(0      )

   __lowerCAmelCase					:	str      =       StableDiffusionDiffEditPipeline.from_pretrained(
       """stabilityai/stable-diffusion-2-1"""       ,  safety_checker=_snake_case       ,  torch_dtype=torch.floataa      )
   __lowerCAmelCase					:	Optional[Any]      =       DDIMScheduler.from_config(pipe.scheduler.config      )
   __lowerCAmelCase					:	int      =       DDIMInverseScheduler.from_config(pipe.scheduler.config      )
   pipe.enable_model_cpu_offload()
   pipe.set_progress_bar_config(disable=_snake_case      )

   __lowerCAmelCase					:	int      =       """a bowl of fruit"""
   __lowerCAmelCase					:	str      =       """a bowl of pears"""

   __lowerCAmelCase					:	Any      =       pipe.generate_mask(
       image=self.raw_image       ,  source_prompt=_snake_case       ,  target_prompt=_snake_case       ,  generator=_snake_case       ,  )

   __lowerCAmelCase					:	Union[str, Any]      =       pipe.invert(
       prompt=_snake_case       ,  image=self.raw_image       ,  inpaint_strength=0.7       ,  generator=_snake_case      ).latents

   __lowerCAmelCase					:	Union[str, Any]      =       pipe(
       prompt=_snake_case       ,  mask_image=_snake_case       ,  image_latents=_snake_case       ,  generator=_snake_case       ,  negative_prompt=_snake_case       ,  inpaint_strength=0.7       ,  output_type="""numpy"""       ,  ).images[0]

   __lowerCAmelCase					:	Optional[int]      =       (
       np.array(
           load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/diffedit/pears.png"""      ).resize((768, 768)      )      )
       / 255
   )
   assert np.abs((expected_image - image).max()      ) < 5E-1






  def 				UpperCAmelCase__						(							self			:					Any      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Dict      =       torch.manual_seed(0      )

   __lowerCAmelCase					:	Optional[Any]      =       StableDiffusionDiffEditPipeline.from_pretrained(
       """stabilityai/stable-diffusion-2-1"""       ,  safety_checker=_snake_case       ,  torch_dtype=torch.floataa      )
   __lowerCAmelCase					:	List[str]      =       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config      )
   __lowerCAmelCase					:	Dict      =       DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config      )
   pipe.enable_model_cpu_offload()
   pipe.set_progress_bar_config(disable=_snake_case      )

   __lowerCAmelCase					:	str      =       """a bowl of fruit"""
   __lowerCAmelCase					:	Optional[int]      =       """a bowl of pears"""

   __lowerCAmelCase					:	Union[str, Any]      =       pipe.generate_mask(
       image=self.raw_image       ,  source_prompt=_snake_case       ,  target_prompt=_snake_case       ,  generator=_snake_case       ,  )

   __lowerCAmelCase					:	str      =       pipe.invert(
       prompt=_snake_case       ,  image=self.raw_image       ,  inpaint_strength=0.7       ,  generator=_snake_case       ,  num_inference_steps=25       ,  ).latents

   __lowerCAmelCase					:	List[str]      =       pipe(
       prompt=_snake_case       ,  mask_image=_snake_case       ,  image_latents=_snake_case       ,  generator=_snake_case       ,  negative_prompt=_snake_case       ,  inpaint_strength=0.7       ,  num_inference_steps=25       ,  output_type="""numpy"""       ,  ).images[0]

   __lowerCAmelCase					:	Any      =       (
       np.array(
           load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/diffedit/pears.png"""      ).resize((768, 768)      )      )
       / 255
   )
   assert np.abs((expected_image - image).max()      ) < 5E-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      )