



"""simple docstring"""





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  lowercase__  (       SCREAMING_SNAKE_CASE ):







       '''simple docstring'''


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


             '''simple docstring'''




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



class  lowercase__  :







       '''simple docstring'''


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


             '''simple docstring'''




             UpperCAmelCase_     					=				parent
             UpperCAmelCase_     					=				batch_size
             UpperCAmelCase_     					=				num_channels
             UpperCAmelCase_     					=				image_size
             UpperCAmelCase_     					=				depth_multiplier
             UpperCAmelCase_     					=				depth_divisible_by
             UpperCAmelCase_     					=				min_depth
             UpperCAmelCase_     					=				expand_ratio
             UpperCAmelCase_     					=				tf_padding
             UpperCAmelCase_     					=				output_stride
             UpperCAmelCase_     					=				first_layer_is_expansion
             UpperCAmelCase_     					=				finegrained_output
             UpperCAmelCase_     					=				hidden_act
             UpperCAmelCase_     					=				last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier       )
             UpperCAmelCase_     					=				classifier_dropout_prob
             UpperCAmelCase_     					=				use_labels
             UpperCAmelCase_     					=				is_training
             UpperCAmelCase_     					=				num_labels
             UpperCAmelCase_     					=				initializer_range
             UpperCAmelCase_     					=				scope



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


             '''simple docstring'''




             UpperCAmelCase_     					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

             UpperCAmelCase_     					=				self.get_config()

             return config, pixel_values, labels, pixel_labels



       def 	lowercase__							(				self     :    Optional[Any]       )					->		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 	lowercase__							(				self     :    int						,							_UpperCAmelCase     :    List[Any]						,							_UpperCAmelCase     :    Dict						,							_UpperCAmelCase     :    Tuple						,							_UpperCAmelCase     :    str       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaModel(config=_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				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 	lowercase__							(				self     :    Dict						,							_UpperCAmelCase     :    Dict						,							_UpperCAmelCase     :    Union[str, Any]						,							_UpperCAmelCase     :    List[Any]						,							_UpperCAmelCase     :    int       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.num_labels
             UpperCAmelCase_     					=				MobileNetVaForImageClassification(_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				model(_UpperCAmelCase						,							labels=_UpperCAmelCase       )
             self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.num_labels)       )



       def 	lowercase__							(				self     :    Dict						,							_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    int						,							_UpperCAmelCase     :    Dict						,							_UpperCAmelCase     :    int       )					->		str:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.num_labels
             UpperCAmelCase_     					=				MobileNetVaForSemanticSegmentation(_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				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,
                 )						,							)
             UpperCAmelCase_     					=				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 	lowercase__							(				self     :    Dict       )					->		List[str]:


             '''simple docstring'''




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



@require_torch
class  lowercase__  (       SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   unittest.TestCase ):







       '''simple docstring'''


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

       UpperCamelCase		=	False
       UpperCamelCase		=	False
       UpperCamelCase		=	False
       UpperCamelCase		=	False



       def 	lowercase__							(				self     :    Tuple       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaModelTester(self       )
             UpperCAmelCase_     					=				MobileNetVaConfigTester(self						,							config_class=_UpperCAmelCase						,							has_text_modality=_UpperCAmelCase       )



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


             '''simple docstring'''




             self.config_tester.run_common_tests()



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


             '''simple docstring'''




             pass



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


             '''simple docstring'''




             pass



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


             '''simple docstring'''




             pass



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


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

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

                   UpperCAmelCase_     					=				["pixel_values"]
                   self.assertListEqual(arg_names[:1]						,							_UpperCAmelCase       )



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_UpperCAmelCase       )



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


             '''simple docstring'''




             def check_hidden_states_output(_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    int       ):
                   UpperCAmelCase_     					=				model_class(_UpperCAmelCase       )
                   model.to(_UpperCAmelCase       )
                   model.eval()

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

                   UpperCAmelCase_     					=				outputs.hidden_states

                   UpperCAmelCase_     					=				16
                   self.assertEqual(len(_UpperCAmelCase       )						,							_UpperCAmelCase       )

             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_     					=				True
                   check_hidden_states_output(_UpperCAmelCase						,							_UpperCAmelCase						,							_UpperCAmelCase       )

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

                   check_hidden_states_output(_UpperCAmelCase						,							_UpperCAmelCase						,							_UpperCAmelCase       )



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase       )



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase       )







       @slow
       def 	lowercase__							(				self     :    List[Any]       )					->		int:


             '''simple docstring'''




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



def   a__      ( ):
      UpperCAmelCase_     					=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
      return image


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







       '''simple docstring'''


       @cached_property
       def 	lowercase__							(				self     :    Any       )					->		Dict:


             '''simple docstring'''




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



       @slow
       def 	lowercase__							(				self     :    Dict       )					->		List[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"       ).to(_UpperCAmelCase       )

             UpperCAmelCase_     					=				self.default_image_processor
             UpperCAmelCase_     					=				prepare_img()
             UpperCAmelCase_     					=				image_processor(images=_UpperCAmelCase						,							return_tensors="pt"       ).to(_UpperCAmelCase       )

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

             # verify the logits
             UpperCAmelCase_     					=				torch.Size((1, 1001)       )
             self.assertEqual(outputs.logits.shape						,							_UpperCAmelCase       )

             UpperCAmelCase_     					=				torch.tensor([0.2445, -1.1993, 0.1905]       ).to(_UpperCAmelCase       )

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







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


             '''simple docstring'''




             UpperCAmelCase_     					=				MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"       )
             UpperCAmelCase_     					=				model.to(_UpperCAmelCase       )

             UpperCAmelCase_     					=				MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"       )

             UpperCAmelCase_     					=				prepare_img()
             UpperCAmelCase_     					=				image_processor(images=_UpperCAmelCase						,							return_tensors="pt"       ).to(_UpperCAmelCase       )

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_     					=				model(**_UpperCAmelCase       )
             UpperCAmelCase_     					=				outputs.logits

             # verify the logits
             UpperCAmelCase_     					=				torch.Size((1, 21, 65, 65)       )
             self.assertEqual(logits.shape						,							_UpperCAmelCase       )

             UpperCAmelCase_     					=				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       )       )








class     A__   :







    """simple docstring"""

    def __init__(			self     ,   __snake_case       ):
         snake_case											=							n
         snake_case											=							[None] * self.n
         snake_case											=							0  # index of the first element
         snake_case											=							0
         snake_case											=							0
    def __len__(			self       ):
         return self.size
    def 						a_     (			self       ):
         return self.size == 0
    def 						a_     (			self       ):
         return False if self.is_empty() else self.array[self.front]
    def 						a_     (			self     ,   __snake_case       ):
         if self.size >= self.n:
              raise Exception('''QUEUE IS FULL'''       )

         snake_case											=							data
         snake_case											=							(self.rear + 1) % self.n
         self.size += 1
         return self




    def 						a_     (			self       ):
         if self.size == 0:
              raise Exception('''UNDERFLOW'''       )

         snake_case											=							self.array[self.front]
         snake_case											=							None
         snake_case											=							(self.front + 1) % self.n
         self.size -= 1
         return temp




