





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, MobileNetVaModel
     from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import MobileNetVaImageProcessor



class 				_UpperCAmelCase    (    _UpperCamelCase    ):

  """simple docstring"""


  def 				lowercase		(				self :		str     )							->						Optional[int]:
     __lowerCAmelCase								=	self.config_class(**self.inputs_dict     )
     self.parent.assertTrue(hasattr(lowerCAmelCase_					,  'tf_padding'     )     )
     self.parent.assertTrue(hasattr(lowerCAmelCase_					,  'depth_multiplier'     )     )





class 				_UpperCAmelCase    :

  """simple docstring"""


  def __init__(				self :		Any					,  lowerCAmelCase_ :		Optional[int]					,  lowerCAmelCase_ :		Optional[Any]=1_3					,  lowerCAmelCase_ :		List[str]=3					,  lowerCAmelCase_ :		str=3_2					,  lowerCAmelCase_ :		Dict=0.25					,  lowerCAmelCase_ :		Optional[Any]=8					,  lowerCAmelCase_ :		Any=True					,  lowerCAmelCase_ :		Dict=1_0_2_4					,  lowerCAmelCase_ :		Optional[Any]=3_2					,  lowerCAmelCase_ :		Optional[int]="relu6"					,  lowerCAmelCase_ :		Any=0.1					,  lowerCAmelCase_ :		Any=0.02					,  lowerCAmelCase_ :		int=True					,  lowerCAmelCase_ :		Optional[Any]=True					,  lowerCAmelCase_ :		str=1_0					,  lowerCAmelCase_ :		Optional[Any]=None					,  )							->						Optional[Any]:
     __lowerCAmelCase								=	parent
     __lowerCAmelCase								=	batch_size
     __lowerCAmelCase								=	num_channels
     __lowerCAmelCase								=	image_size
     __lowerCAmelCase								=	depth_multiplier
     __lowerCAmelCase								=	min_depth
     __lowerCAmelCase								=	tf_padding
     __lowerCAmelCase								=	int(last_hidden_size * depth_multiplier     )
     __lowerCAmelCase								=	output_stride
     __lowerCAmelCase								=	hidden_act
     __lowerCAmelCase								=	classifier_dropout_prob
     __lowerCAmelCase								=	use_labels
     __lowerCAmelCase								=	is_training
     __lowerCAmelCase								=	num_labels
     __lowerCAmelCase								=	initializer_range
     __lowerCAmelCase								=	scope






  def 				lowercase		(				self :		Union[str, Any]     )							->						Tuple:
     __lowerCAmelCase								=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

     __lowerCAmelCase								=	self.get_config()

     return config, pixel_values, labels, pixel_labels






  def 				lowercase		(				self :		Optional[Any]     )							->						Any:
     return MobileNetVaConfig(
         num_channels=self.num_channels					,  image_size=self.image_size					,  depth_multiplier=self.depth_multiplier					,  min_depth=self.min_depth					,  tf_padding=self.tf_padding					,  hidden_act=self.hidden_act					,  classifier_dropout_prob=self.classifier_dropout_prob					,  initializer_range=self.initializer_range					,  )






  def 				lowercase		(				self :		Tuple					,  lowerCAmelCase_ :		Tuple					,  lowerCAmelCase_ :		Any					,  lowerCAmelCase_ :		Any					,  lowerCAmelCase_ :		Tuple     )							->						str:
     __lowerCAmelCase								=	MobileNetVaModel(config=lowerCAmelCase_     )
     model.to(lowerCAmelCase_     )
     model.eval()
     __lowerCAmelCase								=	model(lowerCAmelCase_     )
     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,
         )					,  )






  def 				lowercase		(				self :		Union[str, Any]					,  lowerCAmelCase_ :		Union[str, Any]					,  lowerCAmelCase_ :		Optional[Any]					,  lowerCAmelCase_ :		Optional[Any]					,  lowerCAmelCase_ :		List[str]     )							->						Optional[int]:
     __lowerCAmelCase								=	self.num_labels
     __lowerCAmelCase								=	MobileNetVaForImageClassification(lowerCAmelCase_     )
     model.to(lowerCAmelCase_     )
     model.eval()
     __lowerCAmelCase								=	model(lowerCAmelCase_					,  labels=lowerCAmelCase_     )
     self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_labels)     )






  def 				lowercase		(				self :		Dict     )							->						Any:
     __lowerCAmelCase								=	self.prepare_config_and_inputs()
     __lowerCAmelCase	,	__lowerCAmelCase	,	__lowerCAmelCase	,	__lowerCAmelCase								=	config_and_inputs
     __lowerCAmelCase								=	{'pixel_values': pixel_values}
     return config, inputs_dict





@require_torch
class 				_UpperCAmelCase    (    _UpperCamelCase		,    _UpperCamelCase		,    unittest.TestCase    ):

  """simple docstring"""


  a_        = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
  a_        = (
      {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
      if is_torch_available()
      else {}
  )

  a_        = False
  a_        = False
  a_        = False
  a_        = False






  def 				lowercase		(				self :		str     )							->						Tuple:
     __lowerCAmelCase								=	MobileNetVaModelTester(self     )
     __lowerCAmelCase								=	MobileNetVaConfigTester(self					,  config_class=lowerCAmelCase_					,  has_text_modality=lowerCAmelCase_     )






  def 				lowercase		(				self :		List[str]     )							->						Union[str, Any]:
     self.config_tester.run_common_tests()






  @unittest.skip(reason='MobileNetV1 does not use inputs_embeds'     )
  def 				lowercase		(				self :		Dict     )							->						Tuple:
     pass






  @unittest.skip(reason='MobileNetV1 does not support input and output embeddings'     )
  def 				lowercase		(				self :		Optional[int]     )							->						List[str]:
     pass






  @unittest.skip(reason='MobileNetV1 does not output attentions'     )
  def 				lowercase		(				self :		List[Any]     )							->						List[Any]:
     pass






  def 				lowercase		(				self :		int     )							->						Optional[Any]:
     __lowerCAmelCase	,	__lowerCAmelCase								=	self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCAmelCase								=	['pixel_values']
        self.assertListEqual(arg_names[:1]					,  lowerCAmelCase_     )






  def 				lowercase		(				self :		Any     )							->						Union[str, Any]:
     __lowerCAmelCase								=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_     )






  def 				lowercase		(				self :		List[str]     )							->						str:
     def check_hidden_states_output(lowerCAmelCase_ :		Tuple					,  lowerCAmelCase_ :		int					,  lowerCAmelCase_ :		List[Any]     ):
        __lowerCAmelCase								=	model_class(lowerCAmelCase_     )
        model.to(lowerCAmelCase_     )
        model.eval()

        with torch.no_grad():
           __lowerCAmelCase								=	model(**self._prepare_for_class(lowerCAmelCase_					,  lowerCAmelCase_     )     )

        __lowerCAmelCase								=	outputs.hidden_states

        __lowerCAmelCase								=	2_6
        self.assertEqual(len(lowerCAmelCase_     )					,  lowerCAmelCase_     )

     __lowerCAmelCase	,	__lowerCAmelCase								=	self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __lowerCAmelCase								=	True
        check_hidden_states_output(lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_     )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __lowerCAmelCase								=	True

        check_hidden_states_output(lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_     )






  def 				lowercase		(				self :		Union[str, Any]     )							->						int:
     __lowerCAmelCase								=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_     )






  @slow
  def 				lowercase		(				self :		Any     )							->						int:
     for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase								=	MobileNetVaModel.from_pretrained(lowerCAmelCase_     )
        self.assertIsNotNone(lowerCAmelCase_     )





def   a_    ( ):
   __lowerCAmelCase								=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
   return image




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

  """simple docstring"""


  @cached_property
  def 				lowercase		(				self :		List[str]     )							->						List[Any]:
     return (
         MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'     ) if is_vision_available() else None
     )






  @slow
  def 				lowercase		(				self :		Union[str, Any]     )							->						str:
     __lowerCAmelCase								=	MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'     ).to(lowerCAmelCase_     )

     __lowerCAmelCase								=	self.default_image_processor
     __lowerCAmelCase								=	prepare_img()
     __lowerCAmelCase								=	image_processor(images=lowerCAmelCase_					,  return_tensors='pt'     ).to(lowerCAmelCase_     )

     # forward pass
     with torch.no_grad():
        __lowerCAmelCase								=	model(**lowerCAmelCase_     )

     # verify the logits
     __lowerCAmelCase								=	torch.Size((1, 1_0_0_1)     )
     self.assertEqual(outputs.logits.shape					,  lowerCAmelCase_     )

     __lowerCAmelCase								=	torch.tensor([-4.17_39, -1.12_33, 3.12_05]     ).to(lowerCAmelCase_     )

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








from ..utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
)


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_pt_objects import *  # noqa F403
else:
     from .scheduling_consistency_models import CMStochasticIterativeScheduler
     from .scheduling_ddim import DDIMScheduler
     from .scheduling_ddim_inverse import DDIMInverseScheduler
     from .scheduling_ddim_parallel import DDIMParallelScheduler
     from .scheduling_ddpm import DDPMScheduler
     from .scheduling_ddpm_parallel import DDPMParallelScheduler
     from .scheduling_deis_multistep import DEISMultistepScheduler
     from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
     from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
     from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
     from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
     from .scheduling_euler_discrete import EulerDiscreteScheduler
     from .scheduling_heun_discrete import HeunDiscreteScheduler
     from .scheduling_ipndm import IPNDMScheduler
     from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
     from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
     from .scheduling_karras_ve import KarrasVeScheduler
     from .scheduling_pndm import PNDMScheduler
     from .scheduling_repaint import RePaintScheduler
     from .scheduling_sde_ve import ScoreSdeVeScheduler
     from .scheduling_sde_vp import ScoreSdeVpScheduler
     from .scheduling_unclip import UnCLIPScheduler
     from .scheduling_unipc_multistep import UniPCMultistepScheduler
     from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
     from .scheduling_vq_diffusion import VQDiffusionScheduler

try:
     if not is_flax_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_flax_objects import *  # noqa F403
else:
     from .scheduling_ddim_flax import FlaxDDIMScheduler
     from .scheduling_ddpm_flax import FlaxDDPMScheduler
     from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
     from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
     from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
     from .scheduling_pndm_flax import FlaxPNDMScheduler
     from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
     from .scheduling_utils_flax import (
         FlaxKarrasDiffusionSchedulers,
         FlaxSchedulerMixin,
         FlaxSchedulerOutput,
         broadcast_to_shape_from_left,
     )


try:
     if not (is_torch_available() and is_scipy_available()):
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
     from .scheduling_lms_discrete import LMSDiscreteScheduler

try:
     if not (is_torch_available() and is_torchsde_available()):
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     from ..utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
     from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler

