





import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionInstructPixaPixPipeline,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							unittest.TestCase					):







 '''simple docstring'''
 lowercase_	=    StableDiffusionInstructPixaPixPipeline
 lowercase_	=    TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width", "cross_attention_kwargs"}
 lowercase_	=    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
 lowercase_	=    IMAGE_TO_IMAGE_IMAGE_PARAMS
 lowercase_	=    IMAGE_TO_IMAGE_IMAGE_PARAMS

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Dict:



   '''simple docstring'''



   torch.manual_seed(0)
   lowerCamelCase__:   Tuple    						=UNetaDConditionModel(
       block_out_channels=(32, 64) ,				layers_per_block=2 ,				sample_size=32 ,				in_channels=8 ,				out_channels=4 ,				down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") ,				up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") ,				cross_attention_dim=32 ,				)
   lowerCamelCase__:   str    						=PNDMScheduler(skip_prk_steps=UpperCAmelCase_)
   torch.manual_seed(0)
   lowerCamelCase__:   List[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 ,				)
   torch.manual_seed(0)
   lowerCamelCase__:   List[Any]    						=CLIPTextConfig(
       bos_token_id=0 ,				eos_token_id=2 ,				hidden_size=32 ,				intermediate_size=37 ,				layer_norm_eps=1E-0_5 ,				num_attention_heads=4 ,				num_hidden_layers=5 ,				pad_token_id=1 ,				vocab_size=1_000 ,				)
   lowerCamelCase__:   Optional[int]    						=CLIPTextModel(UpperCAmelCase_)
   lowerCamelCase__:   Union[str, Any]    						=CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

   lowerCamelCase__:   Optional[int]    						={
       "unet": unet,
       "scheduler": scheduler,
       "vae": vae,
       "text_encoder": text_encoder,
       "tokenizer": tokenizer,
       "safety_checker": None,
       "feature_extractor": None,
   }
   return components

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict ,				UpperCAmelCase_       :     List[Any] ,				UpperCAmelCase_       :     int=0) ->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:   List[str]    						=floats_tensor((1, 3, 32, 32) ,				rng=random.Random(UpperCAmelCase_)).to(UpperCAmelCase_)
   lowerCamelCase__:   List[Any]    						=image.cpu().permute(0 ,				2 ,				3 ,				1)[0]
   lowerCamelCase__:   Optional[int]    						=Image.fromarray(np.uinta(UpperCAmelCase_)).convert("RGB")
   if str(UpperCAmelCase_).startswith("mps"):
     lowerCamelCase__:   Any    						=torch.manual_seed(UpperCAmelCase_)
   else:
     lowerCamelCase__:   Optional[Any]    						=torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_)
   lowerCamelCase__:   Tuple    						={
       "prompt": "A painting of a squirrel eating a burger",
       "image": image,
       "generator": generator,
       "num_inference_steps": 2,
       "guidance_scale": 6.0,
       "image_guidance_scale": 1,
       "output_type": "numpy",
   }
   return inputs

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->int:



   '''simple docstring'''



   lowerCamelCase__:   Dict    						="cpu"  # ensure determinism for the device-dependent torch.Generator
   lowerCamelCase__:   List[Any]    						=self.get_dummy_components()
   lowerCamelCase__:   Union[str, Any]    						=StableDiffusionInstructPixaPixPipeline(**UpperCAmelCase_)
   lowerCamelCase__:   Union[str, Any]    						=sd_pipe.to(UpperCAmelCase_)
   sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   lowerCamelCase__:   List[str]    						=self.get_dummy_inputs(UpperCAmelCase_)
   lowerCamelCase__:   str    						=sd_pipe(**UpperCAmelCase_).images
   lowerCamelCase__:   Dict    						=image[0, -3:, -3:, -1]
   assert image.shape == (1, 32, 32, 3)
   lowerCamelCase__:   List[str]    						=np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815])

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

 def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->Any:



   '''simple docstring'''



   lowerCamelCase__:   Optional[int]    						="cpu"  # ensure determinism for the device-dependent torch.Generator
   lowerCamelCase__:   Union[str, Any]    						=self.get_dummy_components()
   lowerCamelCase__:   Dict    						=StableDiffusionInstructPixaPixPipeline(**UpperCAmelCase_)
   lowerCamelCase__:   Any    						=sd_pipe.to(UpperCAmelCase_)
   sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   lowerCamelCase__:   Optional[Any]    						=self.get_dummy_inputs(UpperCAmelCase_)
   lowerCamelCase__:   Tuple    						="french fries"
   lowerCamelCase__:   Optional[Any]    						=sd_pipe(**UpperCAmelCase_ ,				negative_prompt=UpperCAmelCase_)
   lowerCamelCase__:   Any    						=output.images
   lowerCamelCase__:   List[Any]    						=image[0, -3:, -3:, -1]

   assert image.shape == (1, 32, 32, 3)
   lowerCamelCase__:   Dict    						=np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831])

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

 def 							SCREAMING_SNAKE_CASE_      (self       :     str) ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:   str    						="cpu"  # ensure determinism for the device-dependent torch.Generator
   lowerCamelCase__:   Optional[int]    						=self.get_dummy_components()
   lowerCamelCase__:   Tuple    						=StableDiffusionInstructPixaPixPipeline(**UpperCAmelCase_)
   lowerCamelCase__:   List[str]    						=sd_pipe.to(UpperCAmelCase_)
   sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   lowerCamelCase__:   str    						=self.get_dummy_inputs(UpperCAmelCase_)
   lowerCamelCase__:   Union[str, Any]    						=[inputs["prompt"]] * 2

   lowerCamelCase__:   Optional[Any]    						=np.array(inputs["image"]).astype(np.floataa) / 255.0
   lowerCamelCase__:   Union[str, Any]    						=torch.from_numpy(UpperCAmelCase_).unsqueeze(0).to(UpperCAmelCase_)
   lowerCamelCase__:   Tuple    						=image / 2 + 0.5
   lowerCamelCase__:   List[str]    						=image.permute(0 ,				3 ,				1 ,				2)
   lowerCamelCase__:   Tuple    						=image.repeat(2 ,				1 ,				1 ,				1)

   lowerCamelCase__:   str    						=sd_pipe(**UpperCAmelCase_).images
   lowerCamelCase__:   List[Any]    						=image[-1, -3:, -3:, -1]

   assert image.shape == (2, 32, 32, 3)
   lowerCamelCase__:   List[Any]    						=np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579])

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

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



   '''simple docstring'''



   lowerCamelCase__:   Dict    						="cpu"  # ensure determinism for the device-dependent torch.Generator
   lowerCamelCase__:   int    						=self.get_dummy_components()
   lowerCamelCase__:   Optional[int]    						=EulerAncestralDiscreteScheduler(
       beta_start=0.0_0085 ,				beta_end=0.012 ,				beta_schedule="scaled_linear")
   lowerCamelCase__:   Optional[int]    						=StableDiffusionInstructPixaPixPipeline(**UpperCAmelCase_)
   lowerCamelCase__:   Union[str, Any]    						=sd_pipe.to(UpperCAmelCase_)
   sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   lowerCamelCase__:   Any    						=self.get_dummy_inputs(UpperCAmelCase_)
   lowerCamelCase__:   List[str]    						=sd_pipe(**UpperCAmelCase_).images
   lowerCamelCase__:   List[str]    						=image[0, -3:, -3:, -1]

   lowerCamelCase__:   str    						=[round(UpperCAmelCase_ ,				4) for x in image_slice.flatten().tolist()]
   print(",".join([str(UpperCAmelCase_) for x in slice]))

   assert image.shape == (1, 32, 32, 3)
   lowerCamelCase__:   Dict    						=np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986])

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

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->int:



   '''simple docstring'''



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







 def 							SCREAMING_SNAKE_CASE_      (self       :     Any) ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Tuple    						=self.get_dummy_components()
   lowerCamelCase__:   Union[str, Any]    						=StableDiffusionInstructPixaPixPipeline(**UpperCAmelCase_)
   lowerCamelCase__:   List[Any]    						=VaeImageProcessor(do_resize=UpperCAmelCase_ ,				do_normalize=UpperCAmelCase_)
   lowerCamelCase__:   List[str]    						=pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   lowerCamelCase__:   List[Any]    						=pipe(**self.get_dummy_inputs_by_type(UpperCAmelCase_ ,				input_image_type="pt"))[0]

   lowerCamelCase__:   Tuple    						=components["vae"]
   lowerCamelCase__:   List[str]    						=self.get_dummy_inputs_by_type(UpperCAmelCase_ ,				input_image_type="pt")

   for image_param in self.image_latents_params:
     if image_param in inputs.keys():
       lowerCamelCase__:   List[str]    						=vae.encode(inputs[image_param]).latent_dist.mode()

   lowerCamelCase__:   Any    						=pipe(**UpperCAmelCase_)[0]

   lowerCamelCase__:   Tuple    						=np.abs(out - out_latents_inputs).max()
   self.assertLess(UpperCAmelCase_ ,				1E-4 ,				"passing latents as image input generate different result from passing image")



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







 '''simple docstring'''

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



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict ,				UpperCAmelCase_       :     int=0) ->Dict:



   '''simple docstring'''



   lowerCamelCase__:   Dict    						=torch.manual_seed(UpperCAmelCase_)
   lowerCamelCase__:   List[Any]    						=load_image(
       "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg")
   lowerCamelCase__:   str    						={
       "prompt": "turn him into a cyborg",
       "image": image,
       "generator": generator,
       "num_inference_steps": 3,
       "guidance_scale": 7.5,
       "image_guidance_scale": 1.0,
       "output_type": "numpy",
   }
   return inputs

 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Dict:



   '''simple docstring'''



   lowerCamelCase__:   List[Any]    						=StableDiffusionInstructPixaPixPipeline.from_pretrained(
       "timbrooks/instruct-pix2pix" ,				safety_checker=UpperCAmelCase_)
   pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)
   pipe.enable_attention_slicing()

   lowerCamelCase__:   Tuple    						=self.get_inputs()
   lowerCamelCase__:   Any    						=pipe(**UpperCAmelCase_).images
   lowerCamelCase__:   List[Any]    						=image[0, -3:, -3:, -1].flatten()

   assert image.shape == (1, 512, 512, 3)
   lowerCamelCase__:   Dict    						=np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555])

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

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



   '''simple docstring'''



   lowerCamelCase__:   Optional[int]    						=StableDiffusionInstructPixaPixPipeline.from_pretrained(
       "timbrooks/instruct-pix2pix" ,				safety_checker=UpperCAmelCase_)
   lowerCamelCase__:   Dict    						=LMSDiscreteScheduler.from_config(pipe.scheduler.config)
   pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)
   pipe.enable_attention_slicing()

   lowerCamelCase__:   List[str]    						=self.get_inputs()
   lowerCamelCase__:   List[Any]    						=pipe(**UpperCAmelCase_).images
   lowerCamelCase__:   Optional[int]    						=image[0, -3:, -3:, -1].flatten()

   assert image.shape == (1, 512, 512, 3)
   lowerCamelCase__:   int    						=np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301])

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

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



   '''simple docstring'''



   lowerCamelCase__:   str    						=StableDiffusionInstructPixaPixPipeline.from_pretrained(
       "timbrooks/instruct-pix2pix" ,				safety_checker=UpperCAmelCase_)
   lowerCamelCase__:   Dict    						=DDIMScheduler.from_config(pipe.scheduler.config)
   pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)
   pipe.enable_attention_slicing()

   lowerCamelCase__:   Tuple    						=self.get_inputs()
   lowerCamelCase__:   Union[str, Any]    						=pipe(**UpperCAmelCase_).images
   lowerCamelCase__:   str    						=image[0, -3:, -3:, -1].flatten()

   assert image.shape == (1, 512, 512, 3)
   lowerCamelCase__:   Tuple    						=np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753])

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

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->int:



   '''simple docstring'''



   lowerCamelCase__:   List[str]    						=0

   def callback_fn(UpperCAmelCase_       :     int ,				UpperCAmelCase_       :     int ,				UpperCAmelCase_       :     torch.FloatTensor) -> None:
     lowerCamelCase__:   Any    						=True
     nonlocal number_of_steps
     number_of_steps += 1
     if step == 1:
       lowerCamelCase__:   List[str]    						=latents.detach().cpu().numpy()
       assert latents.shape == (1, 4, 64, 64)
       lowerCamelCase__:   Dict    						=latents[0, -3:, -3:, -1]
       lowerCamelCase__:   Dict    						=np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983])

       assert np.abs(latents_slice.flatten() - expected_slice).max() < 5E-2
     elif step == 2:
       lowerCamelCase__:   Union[str, Any]    						=latents.detach().cpu().numpy()
       assert latents.shape == (1, 4, 64, 64)
       lowerCamelCase__:   Optional[int]    						=latents[0, -3:, -3:, -1]
       lowerCamelCase__:   Tuple    						=np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115])

       assert np.abs(latents_slice.flatten() - expected_slice).max() < 5E-2

   lowerCamelCase__:   Any    						=False

   lowerCamelCase__:   Any    						=StableDiffusionInstructPixaPixPipeline.from_pretrained(
       "timbrooks/instruct-pix2pix" ,				safety_checker=UpperCAmelCase_ ,				torch_dtype=torch.floataa)
   lowerCamelCase__:   Tuple    						=pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)
   pipe.enable_attention_slicing()

   lowerCamelCase__:   str    						=self.get_inputs()
   pipe(**UpperCAmelCase_ ,				callback=UpperCAmelCase_ ,				callback_steps=1)
   assert callback_fn.has_been_called
   assert number_of_steps == 3

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->Tuple:



   '''simple docstring'''



   torch.cuda.empty_cache()
   torch.cuda.reset_max_memory_allocated()
   torch.cuda.reset_peak_memory_stats()

   lowerCamelCase__:   str    						=StableDiffusionInstructPixaPixPipeline.from_pretrained(
       "timbrooks/instruct-pix2pix" ,				safety_checker=UpperCAmelCase_ ,				torch_dtype=torch.floataa)
   lowerCamelCase__:   Any    						=pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)
   pipe.enable_attention_slicing(1)
   pipe.enable_sequential_cpu_offload()

   lowerCamelCase__:   Tuple    						=self.get_inputs()
   lowerCamelCase__:   Optional[int]    						=pipe(**UpperCAmelCase_)

   lowerCamelCase__:   int    						=torch.cuda.max_memory_allocated()
   # make sure that less than 2.2 GB is allocated
   assert mem_bytes < 2.2 * 10**9







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



   '''simple docstring'''



   lowerCamelCase__:   str    						=self.get_inputs()
   # resize to resolution that is divisible by 8 but not 16 or 32
   lowerCamelCase__:   Any    						=inputs["image"].resize((504, 504))

   lowerCamelCase__:   Dict    						="timbrooks/instruct-pix2pix"
   lowerCamelCase__:   Union[str, Any]    						=StableDiffusionInstructPixaPixPipeline.from_pretrained(
       UpperCAmelCase_ ,				safety_checker=UpperCAmelCase_ ,				)
   pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)
   pipe.enable_attention_slicing()

   lowerCamelCase__:   Optional[int]    						=pipe(**UpperCAmelCase_)
   lowerCamelCase__:   Tuple    						=output.images[0]

   lowerCamelCase__:   str    						=image[255:258, 383:386, -1]

   assert image.shape == (504, 504, 3)
   lowerCamelCase__:   Optional[int]    						=np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590])

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











import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
     import torch

     from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
     from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import MobileNetVaImageProcessor



class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->Tuple:



   '''simple docstring'''



   lowerCamelCase__:   Dict    						=self.config_class(**self.inputs_dict)
   self.parent.assertTrue(hasattr(UpperCAmelCase_ ,				"tf_padding"))
   self.parent.assertTrue(hasattr(UpperCAmelCase_ ,				"depth_multiplier"))



class      _SCREAMING_SNAKE_CASE		:







 '''simple docstring'''

 def __init__(self       :     int ,				UpperCAmelCase_       :     List[str] ,				UpperCAmelCase_       :     List[Any]=13 ,				UpperCAmelCase_       :     Optional[Any]=3 ,				UpperCAmelCase_       :     Optional[Any]=32 ,				UpperCAmelCase_       :     Any=0.25 ,				UpperCAmelCase_       :     int=8 ,				UpperCAmelCase_       :     Any=8 ,				UpperCAmelCase_       :     Any=6 ,				UpperCAmelCase_       :     str=32 ,				UpperCAmelCase_       :     Any=True ,				UpperCAmelCase_       :     Any=True ,				UpperCAmelCase_       :     List[Any]=True ,				UpperCAmelCase_       :     Dict="relu6" ,				UpperCAmelCase_       :     Optional[int]=1_280 ,				UpperCAmelCase_       :     List[str]=0.1 ,				UpperCAmelCase_       :     Tuple=0.02 ,				UpperCAmelCase_       :     Optional[Any]=True ,				UpperCAmelCase_       :     Tuple=True ,				UpperCAmelCase_       :     Optional[Any]=10 ,				UpperCAmelCase_       :     Optional[int]=None ,				) ->Dict:



   '''simple docstring'''



   lowerCamelCase__:   Any    						=parent
   lowerCamelCase__:   Optional[Any]    						=batch_size
   lowerCamelCase__:   List[str]    						=num_channels
   lowerCamelCase__:   Dict    						=image_size
   lowerCamelCase__:   Tuple    						=depth_multiplier
   lowerCamelCase__:   Tuple    						=depth_divisible_by
   lowerCamelCase__:   List[str]    						=min_depth
   lowerCamelCase__:   List[str]    						=expand_ratio
   lowerCamelCase__:   Union[str, Any]    						=tf_padding
   lowerCamelCase__:   Optional[Any]    						=output_stride
   lowerCamelCase__:   Tuple    						=first_layer_is_expansion
   lowerCamelCase__:   Any    						=finegrained_output
   lowerCamelCase__:   Union[str, Any]    						=hidden_act
   lowerCamelCase__:   Union[str, Any]    						=last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier)
   lowerCamelCase__:   int    						=classifier_dropout_prob
   lowerCamelCase__:   List[str]    						=use_labels
   lowerCamelCase__:   Any    						=is_training
   lowerCamelCase__:   Dict    						=num_labels
   lowerCamelCase__:   Optional[Any]    						=initializer_range
   lowerCamelCase__:   List[Any]    						=scope

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->str:



   '''simple docstring'''



   lowerCamelCase__:   Optional[Any]    						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

   lowerCamelCase__:   Dict    						=None
   lowerCamelCase__:   int    						=None
   if self.use_labels:
     lowerCamelCase__:   List[str]    						=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__:   Any    						=self.get_config()

   return config, pixel_values, labels, pixel_labels

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->Optional[int]:



   '''simple docstring'''



   return MobileNetVaConfig(
       num_channels=self.num_channels ,				image_size=self.image_size ,				depth_multiplier=self.depth_multiplier ,				depth_divisible_by=self.depth_divisible_by ,				min_depth=self.min_depth ,				expand_ratio=self.expand_ratio ,				output_stride=self.output_stride ,				first_layer_is_expansion=self.first_layer_is_expansion ,				finegrained_output=self.finegrained_output ,				hidden_act=self.hidden_act ,				tf_padding=self.tf_padding ,				classifier_dropout_prob=self.classifier_dropout_prob ,				initializer_range=self.initializer_range ,				)

 def 							SCREAMING_SNAKE_CASE_      (self       :     int ,				UpperCAmelCase_       :     Union[str, Any] ,				UpperCAmelCase_       :     Optional[int] ,				UpperCAmelCase_       :     int ,				UpperCAmelCase_       :     List[str]) ->int:



   '''simple docstring'''



   lowerCamelCase__:   List[str]    						=MobileNetVaModel(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   Dict    						=model(UpperCAmelCase_)
   self.parent.assertEqual(
       result.last_hidden_state.shape ,				(
           self.batch_size,
           self.last_hidden_size,
           self.image_size // self.output_stride,
           self.image_size // self.output_stride,
       ) ,				)
   self.parent.assertEqual(
       result.pooler_output.shape ,				(self.batch_size, self.last_hidden_size) ,				)

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any] ,				UpperCAmelCase_       :     List[Any] ,				UpperCAmelCase_       :     Any ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     Tuple) ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:   int    						=self.num_labels
   lowerCamelCase__:   Optional[int]    						=MobileNetVaForImageClassification(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   Tuple    						=model(UpperCAmelCase_ ,				labels=UpperCAmelCase_)
   self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels))

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any] ,				UpperCAmelCase_       :     Union[str, Any] ,				UpperCAmelCase_       :     Tuple ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     List[Any]) ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=self.num_labels
   lowerCamelCase__:   List[str]    						=MobileNetVaForSemanticSegmentation(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   Any    						=model(UpperCAmelCase_)
   self.parent.assertEqual(
       result.logits.shape ,				(
           self.batch_size,
           self.num_labels,
           self.image_size // self.output_stride,
           self.image_size // self.output_stride,
       ) ,				)
   lowerCamelCase__:   List[str]    						=model(UpperCAmelCase_ ,				labels=UpperCAmelCase_)
   self.parent.assertEqual(
       result.logits.shape ,				(
           self.batch_size,
           self.num_labels,
           self.image_size // self.output_stride,
           self.image_size // self.output_stride,
       ) ,				)







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



   '''simple docstring'''



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



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







 '''simple docstring'''
 lowercase_	=    (
     (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
     if is_torch_available()
     else ()
 )
 lowercase_	=    (
     {
         "feature-extraction": MobileNetVaModel,
         "image-classification": MobileNetVaForImageClassification,
         "image-segmentation": MobileNetVaForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 lowercase_	=    False
 lowercase_	=    False
 lowercase_	=    False
 lowercase_	=    False

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Optional[Any]    						=MobileNetVaModelTester(self)
   lowerCamelCase__:   Union[str, Any]    						=MobileNetVaConfigTester(self ,				config_class=UpperCAmelCase_ ,				has_text_modality=UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->int:



   '''simple docstring'''



   self.config_tester.run_common_tests()

 @unittest.skip(reason="MobileNetV2 does not use inputs_embeds")
 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->Any:



   '''simple docstring'''



   pass

 @unittest.skip(reason="MobileNetV2 does not support input and output embeddings")
 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->str:



   '''simple docstring'''



   pass

 @unittest.skip(reason="MobileNetV2 does not output attentions")
 def 							SCREAMING_SNAKE_CASE_      (self       :     Union[str, Any]) ->List[Any]:



   '''simple docstring'''



   pass

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



   '''simple docstring'''



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

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

     lowerCamelCase__:   Union[str, Any]    						=["pixel_values"]
     self.assertListEqual(arg_names[:1] ,				UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->Any:



   '''simple docstring'''



   lowerCamelCase__:   Optional[int]    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase_)

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



   '''simple docstring'''



   def check_hidden_states_output(UpperCAmelCase_       :     List[str] ,				UpperCAmelCase_       :     Optional[Any] ,				UpperCAmelCase_       :     str):
     lowerCamelCase__:   List[str]    						=model_class(UpperCAmelCase_)
     model.to(UpperCAmelCase_)
     model.eval()

     with torch.no_grad():
       lowerCamelCase__:   Any    						=model(**self._prepare_for_class(UpperCAmelCase_ ,				UpperCAmelCase_))

     lowerCamelCase__:   Optional[Any]    						=outputs.hidden_states

     lowerCamelCase__:   List[str]    						=16
     self.assertEqual(len(UpperCAmelCase_) ,				UpperCAmelCase_)

   lowerCamelCase__						,      lowerCamelCase__:   Dict    						=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(UpperCAmelCase_ ,				UpperCAmelCase_ ,				UpperCAmelCase_)

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

     check_hidden_states_output(UpperCAmelCase_ ,				UpperCAmelCase_ ,				UpperCAmelCase_)

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



   '''simple docstring'''



   lowerCamelCase__:   Tuple    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Dict:



   '''simple docstring'''



   lowerCamelCase__:   int    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_)







 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->Union[str, Any]:



   '''simple docstring'''



   for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowerCamelCase__:   Optional[int]    						=MobileNetVaModel.from_pretrained(UpperCAmelCase_)
     self.assertIsNotNone(UpperCAmelCase_)





def   lowerCAmelCase_				( )  ->	List[str]:







  """simple docstring"""





  lowerCamelCase__:   List[Any]    						=Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
  return image






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







 '''simple docstring'''

 @cached_property
 def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->List[str]:



   '''simple docstring'''



   return (
       MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224") if is_vision_available() else None
   )

 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224").to(UpperCAmelCase_)

   lowerCamelCase__:   Dict    						=self.default_image_processor
   lowerCamelCase__:   str    						=prepare_img()
   lowerCamelCase__:   int    						=image_processor(images=UpperCAmelCase_ ,				return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__:   str    						=model(**UpperCAmelCase_)

   # verify the logits
   lowerCamelCase__:   Optional[Any]    						=torch.Size((1, 1_001))
   self.assertEqual(outputs.logits.shape ,				UpperCAmelCase_)

   lowerCamelCase__:   List[str]    						=torch.tensor([0.2445, -1.1993, 0.1905]).to(UpperCAmelCase_)

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







 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:   List[Any]    						=MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")
   lowerCamelCase__:   str    						=model.to(UpperCAmelCase_)

   lowerCamelCase__:   List[Any]    						=MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")

   lowerCamelCase__:   int    						=prepare_img()
   lowerCamelCase__:   int    						=image_processor(images=UpperCAmelCase_ ,				return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__:   str    						=model(**UpperCAmelCase_)
   lowerCamelCase__:   Union[str, Any]    						=outputs.logits

   # verify the logits
   lowerCamelCase__:   Optional[int]    						=torch.Size((1, 21, 65, 65))
   self.assertEqual(logits.shape ,				UpperCAmelCase_)

   lowerCamelCase__:   Union[str, Any]    						=torch.tensor(
       [
           [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
           [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
           [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
       ] ,				device=UpperCAmelCase_ ,				)

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

