
"""simple docstring"""


import inspect
import unittest

from transformers import MobileViTConfig
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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
      from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import MobileViTImageProcessor



class 	__a	(   _lowerCAmelCase						):






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Tuple      )->	int:







              """simple docstring"""
              UpperCamelCase       			=		self.config_class(**self.inputs_dict      )
              self.parent.assertTrue(hasattr(UpperCAmelCase_							,   "hidden_sizes"      )      )
              self.parent.assertTrue(hasattr(UpperCAmelCase_							,   "neck_hidden_sizes"      )      )
              self.parent.assertTrue(hasattr(UpperCAmelCase_							,   "num_attention_heads"      )      )





class 	__a	:






       def __init__(	self			:				int							,   UpperCAmelCase_			:				int							,   UpperCAmelCase_			:				Tuple=13							,   UpperCAmelCase_			:				int=32							,   UpperCAmelCase_			:				Tuple=2							,   UpperCAmelCase_			:				Any=3							,   UpperCAmelCase_			:				Dict=640							,   UpperCAmelCase_			:				str=4							,   UpperCAmelCase_			:				Optional[Any]="silu"							,   UpperCAmelCase_			:				Dict=3							,   UpperCAmelCase_			:				Optional[Any]=32							,   UpperCAmelCase_			:				List[str]=0.1							,   UpperCAmelCase_			:				Optional[int]=0.1							,   UpperCAmelCase_			:				Tuple=0.1							,   UpperCAmelCase_			:				Dict=0.02							,   UpperCAmelCase_			:				List[Any]=True							,   UpperCAmelCase_			:				List[Any]=True							,   UpperCAmelCase_			:				Optional[Any]=10							,   UpperCAmelCase_			:				str=None							,   )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		parent
              UpperCamelCase       			=		batch_size
              UpperCamelCase       			=		image_size
              UpperCamelCase       			=		patch_size
              UpperCamelCase       			=		num_channels
              UpperCamelCase       			=		last_hidden_size
              UpperCamelCase       			=		num_attention_heads
              UpperCamelCase       			=		hidden_act
              UpperCamelCase       			=		conv_kernel_size
              UpperCamelCase       			=		output_stride
              UpperCamelCase       			=		hidden_dropout_prob
              UpperCamelCase       			=		attention_probs_dropout_prob
              UpperCamelCase       			=		classifier_dropout_prob
              UpperCamelCase       			=		use_labels
              UpperCamelCase       			=		is_training
              UpperCamelCase       			=		num_labels
              UpperCamelCase       			=		initializer_range
              UpperCamelCase       			=		scope






       def 						_SCREAMING_SNAKE_CASE							(	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 						_SCREAMING_SNAKE_CASE							(	self			:				Tuple      )->	Dict:







              """simple docstring"""
              return MobileViTConfig(
                  image_size=self.image_size							,   patch_size=self.patch_size							,   num_channels=self.num_channels							,   num_attention_heads=self.num_attention_heads							,   hidden_act=self.hidden_act							,   conv_kernel_size=self.conv_kernel_size							,   output_stride=self.output_stride							,   hidden_dropout_prob=self.hidden_dropout_prob							,   attention_probs_dropout_prob=self.attention_probs_dropout_prob							,   classifier_dropout_prob=self.classifier_dropout_prob							,   initializer_range=self.initializer_range							,   )






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







              """simple docstring"""
              UpperCamelCase       			=		MobileViTModel(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,
                  )							,   )






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







              """simple docstring"""
              UpperCamelCase       			=		self.num_labels
              UpperCamelCase       			=		MobileViTForImageClassification(UpperCAmelCase_      )
              model.to(UpperCAmelCase_      )
              model.eval()
              UpperCamelCase       			=		model(UpperCAmelCase_							,   labels=UpperCAmelCase_      )
              self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_labels)      )






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







              """simple docstring"""
              UpperCamelCase       			=		self.num_labels
              UpperCamelCase       			=		MobileViTForSemanticSegmentation(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 						_SCREAMING_SNAKE_CASE							(	self			:				int      )->	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 	__a	(   _lowerCAmelCase     ,  _lowerCAmelCase     ,  unittest.TestCase						):
       UpperCamelCase_		:       List[Any]				=      (
           (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       UpperCamelCase_		:       int				=      (
           {
               '''feature-extraction''': MobileViTModel,
               '''image-classification''': MobileViTForImageClassification,
               '''image-segmentation''': MobileViTForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       UpperCamelCase_		:       str				=      False
       UpperCamelCase_		:       List[str]				=      False
       UpperCamelCase_		:       Optional[int]				=      False
       UpperCamelCase_		:       Union[str, Any]				=      False






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







              """simple docstring"""
              UpperCamelCase       			=		MobileViTModelTester(self      )
              UpperCamelCase       			=		MobileViTConfigTester(self							,   config_class=UpperCAmelCase_							,   has_text_modality=UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	Any:







              """simple docstring"""
              self.config_tester.run_common_tests()






       @unittest.skip(reason="MobileViT does not use inputs_embeds"      )
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	Optional[int]:







              """simple docstring"""
              pass






       @unittest.skip(reason="MobileViT does not support input and output embeddings"      )
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Union[str, Any]      )->	Union[str, Any]:







              """simple docstring"""
              pass






       @unittest.skip(reason="MobileViT does not output attentions"      )
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	Dict:







              """simple docstring"""
              pass






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







              """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_      )






       @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."      )
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	str:







              """simple docstring"""
              pass






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







              """simple docstring"""
              UpperCamelCase       			=		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_			:				Optional[int]							,   UpperCAmelCase_			:				Optional[Any]							,   UpperCAmelCase_			:				Optional[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       			=		5
                     self.assertEqual(len(UpperCAmelCase_      )							,   UpperCAmelCase_      )

                     # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
                     # with the width and height being successively divided by 2.
                     UpperCamelCase       			=		2
                     for i in range(len(UpperCAmelCase_      )      ):
                            self.assertListEqual(
                                list(hidden_states[i].shape[-2:]      )							,   [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]							,   )
                            divisor *= 2

                     self.assertEqual(self.model_tester.output_stride							,   divisor // 2      )

              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 						_SCREAMING_SNAKE_CASE							(	self			:				Dict      )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_      )






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







              """simple docstring"""
              UpperCamelCase       			=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_      )






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







              """simple docstring"""
              for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCamelCase       			=		MobileViTModel.from_pretrained(UpperCAmelCase_      )
                     self.assertIsNotNone(UpperCAmelCase_      )





def 						lowerCamelCase__      (				)->				str:







       """simple docstring"""
       UpperCamelCase       			=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
       return image



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






       @cached_property
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	Optional[int]:







              """simple docstring"""
              return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"      ) if is_vision_available() else None






       @slow
       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"      ).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, 1_000)      )
              self.assertEqual(outputs.logits.shape							,   UpperCAmelCase_      )

              UpperCamelCase       			=		torch.tensor([-1.9364, -1.2327, -0.4653]      ).to(UpperCAmelCase_      )

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






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







              """simple docstring"""
              UpperCamelCase       			=		MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"      )
              UpperCamelCase       			=		model.to(UpperCAmelCase_      )

              UpperCamelCase       			=		MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"      )

              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, 32, 32)      )
              self.assertEqual(logits.shape							,   UpperCAmelCase_      )

              UpperCamelCase       			=		torch.tensor(
                  [
                      [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
                      [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
                      [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
                  ]							,   device=UpperCAmelCase_							,   )

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






       @slow
       def 						_SCREAMING_SNAKE_CASE							(	self			:				int      )->	Dict:







              """simple docstring"""
              UpperCamelCase       			=		MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"      )
              UpperCamelCase       			=		model.to(UpperCAmelCase_      )

              UpperCamelCase       			=		MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"      )

              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.detach().cpu()

              UpperCamelCase       			=		image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_							,   target_sizes=[(50, 60)]      )
              UpperCamelCase       			=		torch.Size((50, 60)      )
              self.assertEqual(segmentation[0].shape							,   UpperCAmelCase_      )

              UpperCamelCase       			=		image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_      )
              UpperCamelCase       			=		torch.Size((32, 32)      )
              self.assertEqual(segmentation[0].shape							,   UpperCAmelCase_      )







"""simple docstring"""


from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


SCREAMING_SNAKE_CASE			  =  logging.get_logger(__name__)


# General docstring
SCREAMING_SNAKE_CASE			  =  """MobileNetV1Config"""

# Base docstring
SCREAMING_SNAKE_CASE			  =  """google/mobilenet_v1_1.0_224"""
SCREAMING_SNAKE_CASE			  =  [1, 1_024, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE			  =  """google/mobilenet_v1_1.0_224"""
SCREAMING_SNAKE_CASE			  =  """tabby, tabby cat"""


SCREAMING_SNAKE_CASE			  =  [
    """google/mobilenet_v1_1.0_224""",
    """google/mobilenet_v1_0.75_192""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_=None					)->				int:







       """simple docstring"""
       UpperCamelCase       			=		{}

       if isinstance(UpperCAmelCase_		,   UpperCAmelCase_					):
              UpperCamelCase       			=		model.mobilenet_va
       else:
              UpperCamelCase       			=		model

       UpperCamelCase       			=		"MobilenetV1/Conv2d_0/"
       UpperCamelCase       			=		backbone.conv_stem.convolution.weight
       UpperCamelCase       			=		backbone.conv_stem.normalization.bias
       UpperCamelCase       			=		backbone.conv_stem.normalization.weight
       UpperCamelCase       			=		backbone.conv_stem.normalization.running_mean
       UpperCamelCase       			=		backbone.conv_stem.normalization.running_var

       for i in range(13					):
              UpperCamelCase       			=		i + 1
              UpperCamelCase       			=		i * 2

              UpperCamelCase       			=		backbone.layer[pt_index]
              UpperCamelCase       			=		F"MobilenetV1/Conv2d_{tf_index}_depthwise/"
              UpperCamelCase       			=		pointer.convolution.weight
              UpperCamelCase       			=		pointer.normalization.bias
              UpperCamelCase       			=		pointer.normalization.weight
              UpperCamelCase       			=		pointer.normalization.running_mean
              UpperCamelCase       			=		pointer.normalization.running_var

              UpperCamelCase       			=		backbone.layer[pt_index + 1]
              UpperCamelCase       			=		F"MobilenetV1/Conv2d_{tf_index}_pointwise/"
              UpperCamelCase       			=		pointer.convolution.weight
              UpperCamelCase       			=		pointer.normalization.bias
              UpperCamelCase       			=		pointer.normalization.weight
              UpperCamelCase       			=		pointer.normalization.running_mean
              UpperCamelCase       			=		pointer.normalization.running_var

       if isinstance(UpperCAmelCase_		,   UpperCAmelCase_					):
              UpperCamelCase       			=		"MobilenetV1/Logits/Conv2d_1c_1x1/"
              UpperCamelCase       			=		model.classifier.weight
              UpperCamelCase       			=		model.classifier.bias

       return tf_to_pt_map



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_					)->				List[str]:







       """simple docstring"""
       try:
              import numpy as np
              import tensorflow as tf
       except ImportError:
              logger.error(
                  "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
                  "https://www.tensorflow.org/install/ for installation instructions."					)
              raise

       # Load weights from TF model
       UpperCamelCase       			=		tf.train.list_variables(UpperCAmelCase_					)
       UpperCamelCase       			=		{}
       for name, shape in init_vars:
              logger.info(F"Loading TF weight {name} with shape {shape}"					)
              UpperCamelCase       			=		tf.train.load_variable(UpperCAmelCase_		,   UpperCAmelCase_					)
              UpperCamelCase       			=		array

       # Build TF to PyTorch weights loading map
       UpperCamelCase       			=		_build_tf_to_pytorch_map(UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_					)

       for name, pointer in tf_to_pt_map.items():
              logger.info(F"Importing {name}"					)
              if name not in tf_weights:
                     logger.info(F"{name} not in tf pre-trained weights, skipping"					)
                     continue

              UpperCamelCase       			=		tf_weights[name]

              if "depthwise_weights" in name:
                     logger.info("Transposing depthwise"					)
                     UpperCamelCase       			=		np.transpose(UpperCAmelCase_		,   (2, 3, 0, 1)					)
              elif "weights" in name:
                     logger.info("Transposing"					)
                     if len(pointer.shape					) == 2:  # copying into linear layer
                            UpperCamelCase       			=		array.squeeze().transpose()
                     else:
                            UpperCamelCase       			=		np.transpose(UpperCAmelCase_		,   (3, 2, 0, 1)					)

              if pointer.shape != array.shape:
                     raise ValueError(F"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"					)

              logger.info(F"Initialize PyTorch weight {name} {array.shape}"					)
              UpperCamelCase       			=		torch.from_numpy(UpperCAmelCase_					)

              tf_weights.pop(UpperCAmelCase_		,   UpperCAmelCase_					)
              tf_weights.pop(name + "/RMSProp"		,   UpperCAmelCase_					)
              tf_weights.pop(name + "/RMSProp_1"		,   UpperCAmelCase_					)
              tf_weights.pop(name + "/ExponentialMovingAverage"		,   UpperCAmelCase_					)

       logger.info(F"Weights not copied to PyTorch model: {', '.join(tf_weights.keys()					)}"					)
       return model



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_					)->				torch.Tensor:







       """simple docstring"""
       UpperCamelCase			,							UpperCamelCase       			=		features.shape[-2:]
       UpperCamelCase			,							UpperCamelCase       			=		conv_layer.stride
       UpperCamelCase			,							UpperCamelCase       			=		conv_layer.kernel_size

       if in_height % stride_height == 0:
              UpperCamelCase       			=		max(kernel_height - stride_height		,   0					)
       else:
              UpperCamelCase       			=		max(kernel_height - (in_height % stride_height)		,   0					)

       if in_width % stride_width == 0:
              UpperCamelCase       			=		max(kernel_width - stride_width		,   0					)
       else:
              UpperCamelCase       			=		max(kernel_width - (in_width % stride_width)		,   0					)

       UpperCamelCase       			=		pad_along_width // 2
       UpperCamelCase       			=		pad_along_width - pad_left
       UpperCamelCase       			=		pad_along_height // 2
       UpperCamelCase       			=		pad_along_height - pad_top

       UpperCamelCase       			=		(pad_left, pad_right, pad_top, pad_bottom)
       return nn.functional.pad(UpperCAmelCase_		,   UpperCAmelCase_		,   "constant"		,   0.0					)



class 	__a	(   nn.Module						):






       def __init__(	self			:				List[Any]							,   UpperCAmelCase_			:				MobileNetVaConfig							,   UpperCAmelCase_			:				int							,   UpperCAmelCase_			:				int							,   UpperCAmelCase_			:				int							,   UpperCAmelCase_			:				Optional[int] = 1							,   UpperCAmelCase_			:				Optional[int] = 1							,   UpperCAmelCase_			:				bool = False							,   UpperCAmelCase_			:				Optional[bool] = True							,   UpperCAmelCase_			:				Optional[bool or str] = True							,   )->	None:







              """simple docstring"""
              super().__init__()
              UpperCamelCase       			=		config

              if in_channels % groups != 0:
                     raise ValueError(f"Input channels ({in_channels}) are not divisible by {groups} groups."      )
              if out_channels % groups != 0:
                     raise ValueError(f"Output channels ({out_channels}) are not divisible by {groups} groups."      )

              UpperCamelCase       			=		0 if config.tf_padding else int((kernel_size - 1) / 2      )

              UpperCamelCase       			=		nn.Convad(
                  in_channels=UpperCAmelCase_							,   out_channels=UpperCAmelCase_							,   kernel_size=UpperCAmelCase_							,   stride=UpperCAmelCase_							,   padding=UpperCAmelCase_							,   groups=UpperCAmelCase_							,   bias=UpperCAmelCase_							,   padding_mode="zeros"							,   )

              if use_normalization:
                     UpperCamelCase       			=		nn.BatchNormad(
                         num_features=UpperCAmelCase_							,   eps=config.layer_norm_eps							,   momentum=0.9997							,   affine=UpperCAmelCase_							,   track_running_stats=UpperCAmelCase_							,   )
              else:
                     UpperCamelCase       			=		None

              if use_activation:
                     if isinstance(UpperCAmelCase_							,   UpperCAmelCase_      ):
                            UpperCamelCase       			=		ACTaFN[use_activation]
                     elif isinstance(config.hidden_act							,   UpperCAmelCase_      ):
                            UpperCamelCase       			=		ACTaFN[config.hidden_act]
                     else:
                            UpperCamelCase       			=		config.hidden_act
              else:
                     UpperCamelCase       			=		None






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict							,   UpperCAmelCase_			:				torch.Tensor      )->	torch.Tensor:







              """simple docstring"""
              if self.config.tf_padding:
                     UpperCamelCase       			=		apply_tf_padding(UpperCAmelCase_							,   self.convolution      )
              UpperCamelCase       			=		self.convolution(UpperCAmelCase_      )
              if self.normalization is not None:
                     UpperCamelCase       			=		self.normalization(UpperCAmelCase_      )
              if self.activation is not None:
                     UpperCamelCase       			=		self.activation(UpperCAmelCase_      )
              return features





class 	__a	(   _lowerCAmelCase						):
       UpperCamelCase_		:       List[str]				=      MobileNetVaConfig
       UpperCamelCase_		:       Dict				=      load_tf_weights_in_mobilenet_va
       UpperCamelCase_		:       List[str]				=      '''mobilenet_v1'''
       UpperCamelCase_		:       Optional[int]				=      '''pixel_values'''
       UpperCamelCase_		:       List[Any]				=      False






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any							,   UpperCAmelCase_			:				Union[nn.Linear, nn.Convad]      )->	None:







              """simple docstring"""
              if isinstance(UpperCAmelCase_							,   (nn.Linear, nn.Convad)      ):
                     module.weight.data.normal_(mean=0.0							,   std=self.config.initializer_range      )
                     if module.bias is not None:
                            module.bias.data.zero_()
              elif isinstance(UpperCAmelCase_							,   nn.BatchNormad      ):
                     module.bias.data.zero_()
                     module.weight.data.fill_(1.0      )





SCREAMING_SNAKE_CASE			  =  R"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

SCREAMING_SNAKE_CASE			  =  R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`MobileNetV1ImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""



@add_start_docstrings(
    '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.'''     ,  _lowerCAmelCase     ,  )
class 	__a	(   _lowerCAmelCase						):






       def __init__(	self			:				str							,   UpperCAmelCase_			:				MobileNetVaConfig							,   UpperCAmelCase_			:				bool = True      )->	Optional[int]:







              """simple docstring"""
              super().__init__(UpperCAmelCase_      )
              UpperCamelCase       			=		config

              UpperCamelCase       			=		32
              UpperCamelCase       			=		max(int(depth * config.depth_multiplier      )							,   config.min_depth      )

              UpperCamelCase       			=		MobileNetVaConvLayer(
                  UpperCAmelCase_							,   in_channels=config.num_channels							,   out_channels=UpperCAmelCase_							,   kernel_size=3							,   stride=2							,   )

              UpperCamelCase       			=		[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

              UpperCamelCase       			=		nn.ModuleList()
              for i in range(13      ):
                     UpperCamelCase       			=		out_channels

                     if strides[i] == 2 or i == 0:
                            depth *= 2
                            UpperCamelCase       			=		max(int(depth * config.depth_multiplier      )							,   config.min_depth      )

                     self.layer.append(
                         MobileNetVaConvLayer(
                             UpperCAmelCase_							,   in_channels=UpperCAmelCase_							,   out_channels=UpperCAmelCase_							,   kernel_size=3							,   stride=strides[i]							,   groups=UpperCAmelCase_							,   )      )

                     self.layer.append(
                         MobileNetVaConvLayer(
                             UpperCAmelCase_							,   in_channels=UpperCAmelCase_							,   out_channels=UpperCAmelCase_							,   kernel_size=1							,   )      )

              UpperCamelCase       			=		nn.AdaptiveAvgPoolad((1, 1)      ) if add_pooling_layer else None

              # Initialize weights and apply final processing
              self.post_init()






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]							,   UpperCAmelCase_			:				Dict      )->	List[str]:







              """simple docstring"""
              raise NotImplementedError






       @add_start_docstrings_to_model_forward(UpperCAmelCase_      )
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC							,   output_type=UpperCAmelCase_							,   config_class=_CONFIG_FOR_DOC							,   modality="vision"							,   expected_output=_EXPECTED_OUTPUT_SHAPE							,   )
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Tuple							,   UpperCAmelCase_			:				Optional[torch.Tensor] = None							,   UpperCAmelCase_			:				Optional[bool] = None							,   UpperCAmelCase_			:				Optional[bool] = None							,   )->	Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:







              """simple docstring"""
              UpperCamelCase       			=		(
                  output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
              )
              UpperCamelCase       			=		return_dict if return_dict is not None else self.config.use_return_dict

              if pixel_values is None:
                     raise ValueError("You have to specify pixel_values"      )

              UpperCamelCase       			=		self.conv_stem(UpperCAmelCase_      )

              UpperCamelCase       			=		() if output_hidden_states else None

              for i, layer_module in enumerate(self.layer      ):
                     UpperCamelCase       			=		layer_module(UpperCAmelCase_      )

                     if output_hidden_states:
                            UpperCamelCase       			=		all_hidden_states + (hidden_states,)

              UpperCamelCase       			=		hidden_states

              if self.pooler is not None:
                     UpperCamelCase       			=		torch.flatten(self.pooler(UpperCAmelCase_      )							,   start_dim=1      )
              else:
                     UpperCamelCase       			=		None

              if not return_dict:
                     return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None      )

              return BaseModelOutputWithPoolingAndNoAttention(
                  last_hidden_state=UpperCAmelCase_							,   pooler_output=UpperCAmelCase_							,   hidden_states=UpperCAmelCase_							,   )





@add_start_docstrings(
    '''
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''     ,  _lowerCAmelCase     ,  )
class 	__a	(   _lowerCAmelCase						):






       def __init__(	self			:				str							,   UpperCAmelCase_			:				MobileNetVaConfig      )->	None:







              """simple docstring"""
              super().__init__(UpperCAmelCase_      )

              UpperCamelCase       			=		config.num_labels
              UpperCamelCase       			=		MobileNetVaModel(UpperCAmelCase_      )

              UpperCamelCase       			=		self.mobilenet_va.layer[-1].convolution.out_channels

              # Classifier head
              UpperCamelCase       			=		nn.Dropout(config.classifier_dropout_prob							,   inplace=UpperCAmelCase_      )
              UpperCamelCase       			=		nn.Linear(UpperCAmelCase_							,   config.num_labels      ) if config.num_labels > 0 else nn.Identity()

              # Initialize weights and apply final processing
              self.post_init()






       @add_start_docstrings_to_model_forward(UpperCAmelCase_      )
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT							,   output_type=UpperCAmelCase_							,   config_class=_CONFIG_FOR_DOC							,   expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT							,   )
       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]							,   UpperCAmelCase_			:				Optional[torch.Tensor] = None							,   UpperCAmelCase_			:				Optional[bool] = None							,   UpperCAmelCase_			:				Optional[torch.Tensor] = None							,   UpperCAmelCase_			:				Optional[bool] = None							,   )->	Union[tuple, ImageClassifierOutputWithNoAttention]:







              """simple docstring"""
              UpperCamelCase       			=		return_dict if return_dict is not None else self.config.use_return_dict

              UpperCamelCase       			=		self.mobilenet_va(UpperCAmelCase_							,   output_hidden_states=UpperCAmelCase_							,   return_dict=UpperCAmelCase_      )

              UpperCamelCase       			=		outputs.pooler_output if return_dict else outputs[1]

              UpperCamelCase       			=		self.classifier(self.dropout(UpperCAmelCase_      )      )

              UpperCamelCase       			=		None
              if labels is not None:
                     if self.config.problem_type is None:
                            if self.num_labels == 1:
                                   UpperCamelCase       			=		"regression"
                            elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                                   UpperCamelCase       			=		"single_label_classification"
                            else:
                                   UpperCamelCase       			=		"multi_label_classification"

                     if self.config.problem_type == "regression":
                            UpperCamelCase       			=		MSELoss()
                            if self.num_labels == 1:
                                   UpperCamelCase       			=		loss_fct(logits.squeeze()							,   labels.squeeze()      )
                            else:
                                   UpperCamelCase       			=		loss_fct(UpperCAmelCase_							,   UpperCAmelCase_      )
                     elif self.config.problem_type == "single_label_classification":
                            UpperCamelCase       			=		CrossEntropyLoss()
                            UpperCamelCase       			=		loss_fct(logits.view(-1							,   self.num_labels      )							,   labels.view(-1      )      )
                     elif self.config.problem_type == "multi_label_classification":
                            UpperCamelCase       			=		BCEWithLogitsLoss()
                            UpperCamelCase       			=		loss_fct(UpperCAmelCase_							,   UpperCAmelCase_      )

              if not return_dict:
                     UpperCamelCase       			=		(logits,) + outputs[2:]
                     return ((loss,) + output) if loss is not None else output

              return ImageClassifierOutputWithNoAttention(
                  loss=UpperCAmelCase_							,   logits=UpperCAmelCase_							,   hidden_states=outputs.hidden_states							,   )





