






import unittest

import numpy as np

from transformers import is_flax_available
from transformers.testing_utils import require_flax

from ..test_modeling_flax_common import ids_tensor


if is_flax_available():
	import jax
	import jax.numpy as jnp

	from transformers.generation import (
	    FlaxForcedBOSTokenLogitsProcessor,
	    FlaxForcedEOSTokenLogitsProcessor,
	    FlaxLogitsProcessorList,
	    FlaxMinLengthLogitsProcessor,
	    FlaxTemperatureLogitsWarper,
	    FlaxTopKLogitsWarper,
	    FlaxTopPLogitsWarper,
	)

@require_flax
class 		lowerCAmelCase     ( unittest.TestCase			):

					'''simple docstring'''

					def       lowerCAmelCase				(  self				:	Tuple		,     __a				:	int		,     __a				:	int							)			->  int:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     jnp.ones((batch_size, length)							) / length
												return scores



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


												"""simple docstring"""

												__lowercase      :							str				=     None
												__lowercase      :							List[str]				=     20

												__lowercase      :							List[Any]				=     self._get_uniform_logits(batch_size=2		,     length=__a							)

												# tweak scores to not be uniform anymore
												__lowercase      :							Dict				=     scores.at[1, 5].set((1 / length) + 0.1							)  # peak, 1st batch
												__lowercase      :							Dict				=     scores.at[1, 10].set((1 / length) - 0.4							)  # valley, 1st batch

												# compute softmax
												__lowercase      :							Union[str, Any]				=     jax.nn.softmax(__a		,     axis=-1							)

												__lowercase      :							Union[str, Any]				=     FlaxTemperatureLogitsWarper(temperature=0.5							)
												__lowercase      :							Union[str, Any]				=     FlaxTemperatureLogitsWarper(temperature=1.3							)

												__lowercase      :							Optional[Any]				=     jax.nn.softmax(temp_dist_warper_sharper(__a		,     scores.copy()		,     cur_len=__a							)		,     axis=-1							)
												__lowercase      :							int				=     jax.nn.softmax(temp_dist_warper_smoother(__a		,     scores.copy()		,     cur_len=__a							)		,     axis=-1							)

												# uniform distribution stays uniform
												self.assertTrue(jnp.allclose(probs[0, :]		,     warped_prob_sharp[0, :]		,     atol=1E-3							)							)
												self.assertTrue(jnp.allclose(probs[0, :]		,     warped_prob_smooth[0, :]		,     atol=1E-3							)							)

												# sharp peaks get higher, valleys get lower
												self.assertLess(probs[1, :].max()		,     warped_prob_sharp[1, :].max()							)
												self.assertGreater(probs[1, :].min()		,     warped_prob_sharp[1, :].min()							)

												# smooth peaks get lower, valleys get higher
												self.assertGreater(probs[1, :].max()		,     warped_prob_smooth[1, :].max()							)
												self.assertLess(probs[1, :].min()		,     warped_prob_smooth[1, :].min()							)



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


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     None
												__lowercase      :							Optional[Any]				=     10
												__lowercase      :							Optional[Any]				=     2

												# create ramp distribution
												__lowercase      :							Optional[Any]				=     np.broadcast_to(np.arange(__a							)[None, :]		,     (batch_size, vocab_size)							).copy()
												__lowercase      :							Union[str, Any]				=     ramp_logits[1:, : vocab_size // 2] + vocab_size

												__lowercase      :							List[Any]				=     FlaxTopKLogitsWarper(3							)

												__lowercase      :							Union[str, Any]				=     top_k_warp(__a		,     __a		,     cur_len=__a							)

												# check that correct tokens are filtered
												self.assertListEqual(jnp.isinf(scores[0]							).tolist()		,     7 * [True] + 3 * [False]							)
												self.assertListEqual(jnp.isinf(scores[1]							).tolist()		,     2 * [True] + 3 * [False] + 5 * [True]							)

												# check special case
												__lowercase      :							List[Any]				=     5
												__lowercase      :							Dict				=     FlaxTopKLogitsWarper(top_k=1		,     filter_value=0.0		,     min_tokens_to_keep=3							)

												__lowercase      :							Optional[Any]				=     np.broadcast_to(np.arange(__a							)[None, :]		,     (batch_size, length)							).copy()
												__lowercase      :							str				=     top_k_warp_safety_check(__a		,     __a		,     cur_len=__a							)

												# min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
												self.assertListEqual((scores == 0.0).sum(axis=-1							).tolist()		,     [2, 2]							)



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


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     None
												__lowercase      :							int				=     10
												__lowercase      :							Tuple				=     2

												# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
												__lowercase      :							Union[str, Any]				=     np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]]							)							)

												__lowercase      :							Optional[Any]				=     FlaxTopPLogitsWarper(0.8							)
												__lowercase      :							List[Any]				=     np.exp(top_p_warp(__a		,     __a		,     cur_len=__a							)							)

												# dist should be filtered to keep min num values so that sum is >= top_p
												# exp (-inf) => 0
												__lowercase      :							List[Any]				=     np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]							)
												self.assertTrue(np.allclose(__a		,     __a		,     atol=1E-3							)							)

												# check edge cases with negative and extreme logits
												__lowercase      :							List[str]				=     np.broadcast_to(np.arange(__a							)[None, :]		,     (batch_size, vocab_size)							).copy() - (
												    vocab_size // 2
												)

												# make ramp_logits more extreme
												__lowercase      :							Tuple				=     ramp_logits[1] * 100.0

												# make sure at least 2 tokens are kept
												__lowercase      :							List[str]				=     FlaxTopPLogitsWarper(0.9		,     min_tokens_to_keep=2		,     filter_value=0.0							)
												__lowercase      :							Dict				=     top_p_warp(__a		,     __a		,     cur_len=__a							)

												# first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
												self.assertListEqual((filtered_dist != 0.0).sum(axis=-1							).tolist()		,     [3, 2]							)



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


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     20
												__lowercase      :							Optional[int]				=     4
												__lowercase      :							Union[str, Any]				=     0

												__lowercase      :							Dict				=     FlaxMinLengthLogitsProcessor(min_length=10		,     eos_token_id=__a							)

												# check that min length is applied at length 5
												__lowercase      :							Optional[int]				=     ids_tensor((batch_size, 20)		,     vocab_size=20							)
												__lowercase      :							List[Any]				=     5
												__lowercase      :							List[Any]				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							Optional[int]				=     min_dist_processor(__a		,     __a		,     cur_len=__a							)
												self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()		,     4 * [-float("""inf"""							)]							)

												# check that min length is not applied anymore at length 15
												__lowercase      :							List[Any]				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							Any				=     15
												__lowercase      :							int				=     min_dist_processor(__a		,     __a		,     cur_len=__a							)
												self.assertFalse(jnp.isinf(__a							).any()							)



					def       lowerCAmelCase				(  self				:	Dict							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							str				=     20
												__lowercase      :							Optional[Any]				=     4
												__lowercase      :							Optional[Any]				=     0

												__lowercase      :							int				=     FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__a							)

												# check that all scores are -inf except the bos_token_id score
												__lowercase      :							Dict				=     ids_tensor((batch_size, 1)		,     vocab_size=20							)
												__lowercase      :							int				=     1
												__lowercase      :							Any				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							List[str]				=     logits_processor(__a		,     __a		,     cur_len=__a							)
												self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]							).all()							)
												self.assertListEqual(scores[:, bos_token_id].tolist()		,     4 * [0]							)  # score for bos_token_id shold be zero

												# check that bos_token_id is not forced if current length is greater than 1
												__lowercase      :							Any				=     3
												__lowercase      :							List[Any]				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							Any				=     logits_processor(__a		,     __a		,     cur_len=__a							)
												self.assertFalse(jnp.isinf(__a							).any()							)



					def       lowerCAmelCase				(  self				:	str							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							Dict				=     20
												__lowercase      :							Tuple				=     4
												__lowercase      :							str				=     0
												__lowercase      :							Optional[Any]				=     5

												__lowercase      :							Tuple				=     FlaxForcedEOSTokenLogitsProcessor(max_length=__a		,     eos_token_id=__a							)

												# check that all scores are -inf except the eos_token_id when max_length is reached
												__lowercase      :							List[Any]				=     ids_tensor((batch_size, 4)		,     vocab_size=20							)
												__lowercase      :							Union[str, Any]				=     4
												__lowercase      :							int				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							int				=     logits_processor(__a		,     __a		,     cur_len=__a							)
												self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]							).all()							)
												self.assertListEqual(scores[:, eos_token_id].tolist()		,     4 * [0]							)  # score for eos_token_id should be zero

												# check that eos_token_id is not forced if max_length is not reached
												__lowercase      :							List[str]				=     3
												__lowercase      :							List[Any]				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							List[str]				=     logits_processor(__a		,     __a		,     cur_len=__a							)
												self.assertFalse(jnp.isinf(__a							).any()							)



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


												"""simple docstring"""

												__lowercase      :							List[Any]				=     4
												__lowercase      :							Any				=     10
												__lowercase      :							Optional[int]				=     15
												__lowercase      :							int				=     2
												__lowercase      :							Optional[int]				=     1
												__lowercase      :							Optional[Any]				=     15

												# dummy input_ids and scores
												__lowercase      :							Dict				=     ids_tensor((batch_size, sequence_length)		,     __a							)
												__lowercase      :							int				=     input_ids.copy()

												__lowercase      :							int				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							Tuple				=     scores.copy()

												# instantiate all dist processors
												__lowercase      :							int				=     FlaxTemperatureLogitsWarper(temperature=0.5							)
												__lowercase      :							List[Any]				=     FlaxTopKLogitsWarper(3							)
												__lowercase      :							List[str]				=     FlaxTopPLogitsWarper(0.8							)

												# instantiate all logits processors
												__lowercase      :							Optional[Any]				=     FlaxMinLengthLogitsProcessor(min_length=10		,     eos_token_id=__a							)
												__lowercase      :							Tuple				=     FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__a							)
												__lowercase      :							Dict				=     FlaxForcedEOSTokenLogitsProcessor(max_length=__a		,     eos_token_id=__a							)

												__lowercase      :							List[Any]				=     10

												# no processor list
												__lowercase      :							Any				=     temp_dist_warp(__a		,     __a		,     cur_len=__a							)
												__lowercase      :							Dict				=     top_k_warp(__a		,     __a		,     cur_len=__a							)
												__lowercase      :							List[str]				=     top_p_warp(__a		,     __a		,     cur_len=__a							)
												__lowercase      :							int				=     min_dist_proc(__a		,     __a		,     cur_len=__a							)
												__lowercase      :							Any				=     bos_dist_proc(__a		,     __a		,     cur_len=__a							)
												__lowercase      :							Any				=     eos_dist_proc(__a		,     __a		,     cur_len=__a							)

												# with processor list
												__lowercase      :							Dict				=     FlaxLogitsProcessorList(
												    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]							)
												__lowercase      :							str				=     processor(__a		,     __a		,     cur_len=__a							)

												# scores should be equal
												self.assertTrue(jnp.allclose(__a		,     __a		,     atol=1E-3							)							)

												# input_ids should never be changed
												self.assertListEqual(input_ids.tolist()		,     input_ids_comp.tolist()							)



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


												"""simple docstring"""

												__lowercase      :							List[Any]				=     4
												__lowercase      :							str				=     10
												__lowercase      :							Tuple				=     15
												__lowercase      :							str				=     2
												__lowercase      :							List[str]				=     1
												__lowercase      :							List[str]				=     15

												# dummy input_ids and scores
												__lowercase      :							str				=     ids_tensor((batch_size, sequence_length)		,     __a							)
												__lowercase      :							str				=     input_ids.copy()

												__lowercase      :							int				=     self._get_uniform_logits(__a		,     __a							)
												__lowercase      :							List[Any]				=     scores.copy()

												# instantiate all dist processors
												__lowercase      :							int				=     FlaxTemperatureLogitsWarper(temperature=0.5							)
												__lowercase      :							str				=     FlaxTopKLogitsWarper(3							)
												__lowercase      :							List[str]				=     FlaxTopPLogitsWarper(0.8							)

												# instantiate all logits processors
												__lowercase      :							Any				=     FlaxMinLengthLogitsProcessor(min_length=10		,     eos_token_id=__a							)
												__lowercase      :							Tuple				=     FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__a							)
												__lowercase      :							Dict				=     FlaxForcedEOSTokenLogitsProcessor(max_length=__a		,     eos_token_id=__a							)

												__lowercase      :							int				=     10

												# no processor list
												def run_no_processor_list(__a				:	Optional[Any]		,     __a				:	List[str]		,     __a				:	Union[str, Any]							):
																			__lowercase      :							str				=     temp_dist_warp(__a		,     __a		,     cur_len=__a							)
																			__lowercase      :							List[Any]				=     top_k_warp(__a		,     __a		,     cur_len=__a							)
																			__lowercase      :							Dict				=     top_p_warp(__a		,     __a		,     cur_len=__a							)
																			__lowercase      :							int				=     min_dist_proc(__a		,     __a		,     cur_len=__a							)
																			__lowercase      :							str				=     bos_dist_proc(__a		,     __a		,     cur_len=__a							)
																			__lowercase      :							Union[str, Any]				=     eos_dist_proc(__a		,     __a		,     cur_len=__a							)
																			return scores

												# with processor list
												def run_processor_list(__a				:	Optional[Any]		,     __a				:	int		,     __a				:	Dict							):
																			__lowercase      :							Optional[Any]				=     FlaxLogitsProcessorList(
																			    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]							)
																			__lowercase      :							Optional[Any]				=     processor(__a		,     __a		,     cur_len=__a							)
																			return scores

												__lowercase      :							int				=     jax.jit(__a							)
												__lowercase      :							Optional[int]				=     jax.jit(__a							)

												__lowercase      :							str				=     jitted_run_no_processor_list(__a		,     __a		,     __a							)
												__lowercase      :							List[str]				=     jitted_run_processor_list(__a		,     __a		,     __a							)

												# scores should be equal
												self.assertTrue(jnp.allclose(__a		,     __a		,     atol=1E-3							)							)

												# input_ids should never be changed
												self.assertListEqual(input_ids.tolist()		,     input_ids_comp.tolist()							)







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 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

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


												"""simple docstring"""

												__lowercase      :							str				=     self.config_class(**self.inputs_dict							)
												self.parent.assertTrue(hasattr(__a		,     """tf_padding"""							)							)
												self.parent.assertTrue(hasattr(__a		,     """depth_multiplier"""							)							)







class 		lowerCAmelCase     :

					'''simple docstring'''

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


												"""simple docstring"""

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



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


												"""simple docstring"""

												__lowercase      :							Tuple				=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

												__lowercase      :							List[Any]				=     self.get_config()

												return config, pixel_values, labels, pixel_labels



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


												"""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       lowerCAmelCase				(  self				:	Tuple		,     __a				:	Dict		,     __a				:	Tuple		,     __a				:	Optional[int]		,     __a				:	Union[str, Any]							)			->  List[Any]:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     MobileNetVaModel(config=__a							)
												model.to(__a							)
												model.eval()
												__lowercase      :							Tuple				=     model(__a							)
												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       lowerCAmelCase				(  self				:	List[str]		,     __a				:	Optional[int]		,     __a				:	List[str]		,     __a				:	str		,     __a				:	Optional[int]							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							List[Any]				=     self.num_labels
												__lowercase      :							Dict				=     MobileNetVaForImageClassification(__a							)
												model.to(__a							)
												model.eval()
												__lowercase      :							Dict				=     model(__a		,     labels=__a							)
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)							)



					def       lowerCAmelCase				(  self				:	int		,     __a				:	List[str]		,     __a				:	Tuple		,     __a				:	Any		,     __a				:	List[str]							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							int				=     self.num_labels
												__lowercase      :							List[Any]				=     MobileNetVaForSemanticSegmentation(__a							)
												model.to(__a							)
												model.eval()
												__lowercase      :							Dict				=     model(__a							)
												self.parent.assertEqual(
												    result.logits.shape		,     (
												        self.batch_size,
												        self.num_labels,
												        self.image_size // self.output_stride,
												        self.image_size // self.output_stride,
												    )		,     )
												__lowercase      :							str				=     model(__a		,     labels=__a							)
												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       lowerCAmelCase				(  self				:	Tuple							)			->  Optional[int]:


												"""simple docstring"""

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







@require_torch
class 		lowerCAmelCase     ( __a      ,       __a      ,       unittest.TestCase			):

					'''simple docstring'''

					_A						:			Tuple									=      (
					    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
					    if is_torch_available()
					    else ()
					)
					_A						:			Optional[Any]									=      (
					    {
					        '''feature-extraction''': MobileNetVaModel,
					        '''image-classification''': MobileNetVaForImageClassification,
					        '''image-segmentation''': MobileNetVaForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					_A						:			Tuple									=      False
					_A						:			List[str]									=      False
					_A						:			List[str]									=      False
					_A						:			Optional[int]									=      False



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


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     MobileNetVaModelTester(self							)
												__lowercase      :							int				=     MobileNetVaConfigTester(self		,     config_class=__a		,     has_text_modality=__a							)



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


												"""simple docstring"""

												self.config_tester.run_common_tests()



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


												"""simple docstring"""

												pass



					@unittest.skip(reason="""MobileNetV2 does not support input and output embeddings"""							)
					def       lowerCAmelCase				(  self				:	Any							)			->  Tuple:


												"""simple docstring"""

												pass



					@unittest.skip(reason="""MobileNetV2 does not output attentions"""							)
					def       lowerCAmelCase				(  self				:	List[str]							)			->  int:


												"""simple docstring"""

												pass



					def       lowerCAmelCase				(  self				:	List[str]							)			->  Dict:


												"""simple docstring"""

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

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

																			__lowercase      :							Any				=     ["""pixel_values"""]
																			self.assertListEqual(arg_names[:1]		,     __a							)



					def       lowerCAmelCase				(  self				:	Dict							)			->  Any:


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__a							)



					def       lowerCAmelCase				(  self				:	List[str]							)			->  Tuple:


												"""simple docstring"""

												def check_hidden_states_output(__a				:	List[Any]		,     __a				:	Tuple		,     __a				:	List[str]							):
																			__lowercase      :							Optional[Any]				=     model_class(__a							)
																			model.to(__a							)
																			model.eval()

																			with torch.no_grad():
																										__lowercase      :							List[Any]				=     model(**self._prepare_for_class(__a		,     __a							)							)

																			__lowercase      :							Tuple				=     outputs.hidden_states

																			__lowercase      :							str				=     16
																			self.assertEqual(len(__a							)		,     __a							)

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

												for model_class in self.all_model_classes:
																			__lowercase      :							Any				=     True
																			check_hidden_states_output(__a		,     __a		,     __a							)

																			# check that output_hidden_states also work using config
																			del inputs_dict["output_hidden_states"]
																			__lowercase      :							Union[str, Any]				=     True

																			check_hidden_states_output(__a		,     __a		,     __a							)



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


												"""simple docstring"""

												__lowercase      :							Dict				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__a							)



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


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_semantic_segmentation(*__a							)



					@slow
					def       lowerCAmelCase				(  self				:	Optional[int]							)			->  Optional[Any]:


												"""simple docstring"""

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







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



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

					'''simple docstring'''

					@cached_property
					def       lowerCAmelCase				(  self				:	Any							)			->  Union[str, Any]:


												"""simple docstring"""

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



					@slow
					def       lowerCAmelCase				(  self				:	str							)			->  int:


												"""simple docstring"""

												__lowercase      :							Tuple				=     MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224"""							).to(__a							)

												__lowercase      :							str				=     self.default_image_processor
												__lowercase      :							Tuple				=     prepare_img()
												__lowercase      :							Tuple				=     image_processor(images=__a		,     return_tensors="""pt"""							).to(__a							)

												# forward pass
												with torch.no_grad():
																			__lowercase      :							str				=     model(**__a							)

												# verify the logits
												__lowercase      :							Union[str, Any]				=     torch.Size((1, 1001)							)
												self.assertEqual(outputs.logits.shape		,     __a							)

												__lowercase      :							str				=     torch.tensor([0.2445, -1.1993, 0.1905]							).to(__a							)

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



					@slow
					def       lowerCAmelCase				(  self				:	Tuple							)			->  Any:


												"""simple docstring"""

												__lowercase      :							int				=     MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513"""							)
												__lowercase      :							Dict				=     model.to(__a							)

												__lowercase      :							Tuple				=     MobileNetVaImageProcessor.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513"""							)

												__lowercase      :							List[str]				=     prepare_img()
												__lowercase      :							Optional[int]				=     image_processor(images=__a		,     return_tensors="""pt"""							).to(__a							)

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

												# verify the logits
												__lowercase      :							Dict				=     torch.Size((1, 21, 65, 65)							)
												self.assertEqual(logits.shape		,     __a							)

												__lowercase      :							str				=     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=__a		,     )

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