






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


lowercase__          = logging.get_logger(__name__)


# General docstring
lowercase__          = """MobileNetV1Config"""

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

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


lowercase__          = [
    """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       )						->    Any:

		"""simple docstring"""







		lowerCAmelCase_   :							Optional[Any]									=			{}

		if isinstance(a_      ,       a_       ):
				lowerCAmelCase_   :							Optional[Any]									=			model.mobilenet_va
		else:
				lowerCAmelCase_   :							Dict									=			model

		lowerCAmelCase_   :							List[str]									=			'''MobilenetV1/Conv2d_0/'''
		lowerCAmelCase_   :							Dict									=			backbone.conv_stem.convolution.weight
		lowerCAmelCase_   :							Union[str, Any]									=			backbone.conv_stem.normalization.bias
		lowerCAmelCase_   :							Union[str, Any]									=			backbone.conv_stem.normalization.weight
		lowerCAmelCase_   :							str									=			backbone.conv_stem.normalization.running_mean
		lowerCAmelCase_   :							List[str]									=			backbone.conv_stem.normalization.running_var

		for i in range(13       ):
				lowerCAmelCase_   :							Optional[int]									=			i + 1
				lowerCAmelCase_   :							Any									=			i * 2

				lowerCAmelCase_   :							List[Any]									=			backbone.layer[pt_index]
				lowerCAmelCase_   :							int									=			f'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
				lowerCAmelCase_   :							Dict									=			pointer.convolution.weight
				lowerCAmelCase_   :							List[str]									=			pointer.normalization.bias
				lowerCAmelCase_   :							Optional[Any]									=			pointer.normalization.weight
				lowerCAmelCase_   :							str									=			pointer.normalization.running_mean
				lowerCAmelCase_   :							Union[str, Any]									=			pointer.normalization.running_var

				lowerCAmelCase_   :							Dict									=			backbone.layer[pt_index + 1]
				lowerCAmelCase_   :							Tuple									=			f'''MobilenetV1/Conv2d_{tf_index}_pointwise/'''
				lowerCAmelCase_   :							str									=			pointer.convolution.weight
				lowerCAmelCase_   :							str									=			pointer.normalization.bias
				lowerCAmelCase_   :							List[str]									=			pointer.normalization.weight
				lowerCAmelCase_   :							Tuple									=			pointer.normalization.running_mean
				lowerCAmelCase_   :							int									=			pointer.normalization.running_var

		if isinstance(a_      ,       a_       ):
				lowerCAmelCase_   :							str									=			'''MobilenetV1/Logits/Conv2d_1c_1x1/'''
				lowerCAmelCase_   :							List[str]									=			model.classifier.weight
				lowerCAmelCase_   :							Union[str, Any]									=			model.classifier.bias

		return tf_to_pt_map

def 		__lowerCamelCase	(  __UpperCamelCase      ,       __UpperCamelCase      ,       __UpperCamelCase       )						->    Optional[int]:

		"""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
		lowerCAmelCase_   :							List[str]									=			tf.train.list_variables(a_       )
		lowerCAmelCase_   :							Any									=			{}
		for name, shape in init_vars:
				logger.info(f'''Loading TF weight {name} with shape {shape}'''       )
				lowerCAmelCase_   :							int									=			tf.train.load_variable(a_      ,       a_       )
				lowerCAmelCase_   :							Any									=			array

		# Build TF to PyTorch weights loading map
		lowerCAmelCase_   :							List[Any]									=			_build_tf_to_pytorch_map(a_      ,       a_      ,       a_       )

		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

				lowerCAmelCase_   :							Dict									=			tf_weights[name]

				if "depthwise_weights" in name:
						logger.info("Transposing depthwise"       )
						lowerCAmelCase_   :							List[Any]									=			np.transpose(a_      ,       (2, 3, 0, 1)       )
				elif "weights" in name:
						logger.info("Transposing"       )
						if len(pointer.shape       ) == 2:  # copying into linear layer
								lowerCAmelCase_   :							Tuple									=			array.squeeze().transpose()
						else:
								lowerCAmelCase_   :							str									=			np.transpose(a_      ,       (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}'''       )
				lowerCAmelCase_   :							List[Any]									=			torch.from_numpy(a_       )

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

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

def 		__lowerCamelCase	(  __UpperCamelCase      ,       __UpperCamelCase       )						->    torch.Tensor:

		"""simple docstring"""







		lowerCAmelCase_   :							Optional[Any]									=			features.shape[-2:]
		lowerCAmelCase_   :							Dict									=			conv_layer.stride
		lowerCAmelCase_   :							List[Any]									=			conv_layer.kernel_size

		if in_height % stride_height == 0:
				lowerCAmelCase_   :							Tuple									=			max(kernel_height - stride_height      ,       0       )
		else:
				lowerCAmelCase_   :							Dict									=			max(kernel_height - (in_height % stride_height)      ,       0       )

		if in_width % stride_width == 0:
				lowerCAmelCase_   :							int									=			max(kernel_width - stride_width      ,       0       )
		else:
				lowerCAmelCase_   :							List[Any]									=			max(kernel_width - (in_width % stride_width)      ,       0       )

		lowerCAmelCase_   :							str									=			pad_along_width // 2
		lowerCAmelCase_   :							Union[str, Any]									=			pad_along_width - pad_left
		lowerCAmelCase_   :							str									=			pad_along_height // 2
		lowerCAmelCase_   :							Dict									=			pad_along_height - pad_top

		lowerCAmelCase_   :							Optional[Any]									=			(pad_left, pad_right, pad_top, pad_bottom)
		return nn.functional.pad(a_      ,       a_      ,       "constant"      ,       0.0       )


class 		__lowerCamelCase				( nn.Module			):





		'''simple docstring'''






		def __init__(   self							:	List[str]						,			a_							:	str						,			a_							:	Tuple						,			a_							:	Optional[int]						,			a_							:	Union[str, Any]						,			a_							:	Optional[int] = 1						,			a_							:	str = 1						,			a_							:	Tuple = False						,			a_							:	int = True						,			a_							:	Dict = True						,			):
				super().__init__()
				lowerCAmelCase_   :							str									=			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.'''	)

				lowerCAmelCase_   :							List[Any]									=			0 if config.tf_padding else int((kernel_size - 1) / 2	)

				lowerCAmelCase_   :							Optional[int]									=			nn.Convad(
				    in_channels=SCREAMING_SNAKE_CASE__						,			out_channels=SCREAMING_SNAKE_CASE__						,			kernel_size=SCREAMING_SNAKE_CASE__						,			stride=SCREAMING_SNAKE_CASE__						,			padding=SCREAMING_SNAKE_CASE__						,			groups=SCREAMING_SNAKE_CASE__						,			bias=SCREAMING_SNAKE_CASE__						,			padding_mode="zeros"						,			)

				if use_normalization:
						lowerCAmelCase_   :							int									=			nn.BatchNormad(
						    num_features=SCREAMING_SNAKE_CASE__						,			eps=config.layer_norm_eps						,			momentum=0.9997						,			affine=SCREAMING_SNAKE_CASE__						,			track_running_stats=SCREAMING_SNAKE_CASE__						,			)
				else:
						lowerCAmelCase_   :							str									=			None

				if use_activation:
						if isinstance(SCREAMING_SNAKE_CASE__						,			SCREAMING_SNAKE_CASE__	):
								lowerCAmelCase_   :							Any									=			ACTaFN[use_activation]
						elif isinstance(config.hidden_act						,			SCREAMING_SNAKE_CASE__	):
								lowerCAmelCase_   :							int									=			ACTaFN[config.hidden_act]
						else:
								lowerCAmelCase_   :							List[Any]									=			config.hidden_act
				else:
						lowerCAmelCase_   :							Any									=			None





		def    lowerCamelCase       (   self							:	int						,			a_							:	str	):






				if self.config.tf_padding:
						lowerCAmelCase_   :							List[str]									=			apply_tf_padding(SCREAMING_SNAKE_CASE__						,			self.convolution	)
				lowerCAmelCase_   :							List[str]									=			self.convolution(SCREAMING_SNAKE_CASE__	)
				if self.normalization is not None:
						lowerCAmelCase_   :							List[str]									=			self.normalization(SCREAMING_SNAKE_CASE__	)
				if self.activation is not None:
						lowerCAmelCase_   :							Optional[int]									=			self.activation(SCREAMING_SNAKE_CASE__	)
				return features







class 		__lowerCamelCase				( A__			):





		'''simple docstring'''






		a_	:				Dict            =							MobileNetVaConfig
		a_	:				Optional[Any]            =							load_tf_weights_in_mobilenet_va
		a_	:				Tuple            =							'''mobilenet_v1'''
		a_	:				List[str]            =							'''pixel_values'''
		a_	:				Optional[Any]            =							False





		def    lowerCamelCase       (   self							:	int						,			a_							:	List[Any]	):






				if isinstance(SCREAMING_SNAKE_CASE__						,			(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(SCREAMING_SNAKE_CASE__						,			nn.BatchNormad	):
						module.bias.data.zero_()
						module.weight.data.fill_(1.0	)







lowercase__          = r"""\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"""

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


@add_start_docstrings(
    """The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.""" ,							A__ ,							)
class 		__lowerCamelCase				( A__			):





		'''simple docstring'''






		def __init__(   self							:	Union[str, Any]						,			a_							:	Union[str, Any]						,			a_							:	Any = True	):
				super().__init__(SCREAMING_SNAKE_CASE__	)
				lowerCAmelCase_   :							List[Any]									=			config

				lowerCAmelCase_   :							Optional[Any]									=			32
				lowerCAmelCase_   :							List[str]									=			max(int(depth * config.depth_multiplier	)						,			config.min_depth	)

				lowerCAmelCase_   :							int									=			MobileNetVaConvLayer(
				    SCREAMING_SNAKE_CASE__						,			in_channels=config.num_channels						,			out_channels=SCREAMING_SNAKE_CASE__						,			kernel_size=3						,			stride=2						,			)

				lowerCAmelCase_   :							Any									=			[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

				lowerCAmelCase_   :							Optional[Any]									=			nn.ModuleList()
				for i in range(13	):
						lowerCAmelCase_   :							Tuple									=			out_channels

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

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

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

				lowerCAmelCase_   :							Dict									=			nn.AdaptiveAvgPoolad((1, 1)	) if add_pooling_layer else None

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





		def    lowerCamelCase       (   self							:	Any						,			a_							:	Tuple	):
				raise NotImplementedError





		@add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__	)
		@add_code_sample_docstrings(
		    checkpoint=_CHECKPOINT_FOR_DOC						,			output_type=SCREAMING_SNAKE_CASE__						,			config_class=_CONFIG_FOR_DOC						,			modality="vision"						,			expected_output=_EXPECTED_OUTPUT_SHAPE						,			)
		def    lowerCamelCase       (   self							:	int						,			a_							:	Optional[int] = None						,			a_							:	Dict = None						,			a_							:	List[Any] = None						,			):
				lowerCAmelCase_   :							Any									=			(
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)
				lowerCAmelCase_   :							Any									=			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"	)

				lowerCAmelCase_   :							Tuple									=			self.conv_stem(SCREAMING_SNAKE_CASE__	)

				lowerCAmelCase_   :							str									=			() if output_hidden_states else None

				for i, layer_module in enumerate(self.layer	):
						lowerCAmelCase_   :							Tuple									=			layer_module(SCREAMING_SNAKE_CASE__	)

						if output_hidden_states:
								lowerCAmelCase_   :							List[Any]									=			all_hidden_states + (hidden_states,)

				lowerCAmelCase_   :							Tuple									=			hidden_states

				if self.pooler is not None:
						lowerCAmelCase_   :							str									=			torch.flatten(self.pooler(SCREAMING_SNAKE_CASE__	)						,			start_dim=1	)
				else:
						lowerCAmelCase_   :							Dict									=			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=SCREAMING_SNAKE_CASE__						,			pooler_output=SCREAMING_SNAKE_CASE__						,			hidden_states=SCREAMING_SNAKE_CASE__						,			)







@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.
    """ ,							A__ ,							)
class 		__lowerCamelCase				( A__			):





		'''simple docstring'''






		def __init__(   self							:	List[Any]						,			a_							:	int	):
				super().__init__(SCREAMING_SNAKE_CASE__	)

				lowerCAmelCase_   :							Optional[Any]									=			config.num_labels
				lowerCAmelCase_   :							Any									=			MobileNetVaModel(SCREAMING_SNAKE_CASE__	)

				lowerCAmelCase_   :							int									=			self.mobilenet_va.layer[-1].convolution.out_channels

				# Classifier head
				lowerCAmelCase_   :							Any									=			nn.Dropout(config.classifier_dropout_prob						,			inplace=SCREAMING_SNAKE_CASE__	)
				lowerCAmelCase_   :							str									=			nn.Linear(SCREAMING_SNAKE_CASE__						,			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(SCREAMING_SNAKE_CASE__	)
		@add_code_sample_docstrings(
		    checkpoint=_IMAGE_CLASS_CHECKPOINT						,			output_type=SCREAMING_SNAKE_CASE__						,			config_class=_CONFIG_FOR_DOC						,			expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT						,			)
		def    lowerCamelCase       (   self							:	List[str]						,			a_							:	Union[str, Any] = None						,			a_							:	List[str] = None						,			a_							:	Optional[int] = None						,			a_							:	int = None						,			):
				lowerCAmelCase_   :							List[Any]									=			return_dict if return_dict is not None else self.config.use_return_dict

				lowerCAmelCase_   :							Tuple									=			self.mobilenet_va(SCREAMING_SNAKE_CASE__						,			output_hidden_states=SCREAMING_SNAKE_CASE__						,			return_dict=SCREAMING_SNAKE_CASE__	)

				lowerCAmelCase_   :							Tuple									=			outputs.pooler_output if return_dict else outputs[1]

				lowerCAmelCase_   :							str									=			self.classifier(self.dropout(SCREAMING_SNAKE_CASE__	)	)

				lowerCAmelCase_   :							Any									=			None
				if labels is not None:
						if self.config.problem_type is None:
								if self.num_labels == 1:
										lowerCAmelCase_   :							Any									=			'''regression'''
								elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
										lowerCAmelCase_   :							List[Any]									=			'''single_label_classification'''
								else:
										lowerCAmelCase_   :							Tuple									=			'''multi_label_classification'''

						if self.config.problem_type == "regression":
								lowerCAmelCase_   :							Union[str, Any]									=			MSELoss()
								if self.num_labels == 1:
										lowerCAmelCase_   :							Optional[int]									=			loss_fct(logits.squeeze()						,			labels.squeeze()	)
								else:
										lowerCAmelCase_   :							str									=			loss_fct(SCREAMING_SNAKE_CASE__						,			SCREAMING_SNAKE_CASE__	)
						elif self.config.problem_type == "single_label_classification":
								lowerCAmelCase_   :							Union[str, Any]									=			CrossEntropyLoss()
								lowerCAmelCase_   :							Dict									=			loss_fct(logits.view(-1						,			self.num_labels	)						,			labels.view(-1	)	)
						elif self.config.problem_type == "multi_label_classification":
								lowerCAmelCase_   :							Optional[int]									=			BCEWithLogitsLoss()
								lowerCAmelCase_   :							List[str]									=			loss_fct(SCREAMING_SNAKE_CASE__						,			SCREAMING_SNAKE_CASE__	)

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

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







"""simple docstring"""
from typing import TYPE_CHECKING

from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
from ...utils import OptionalDependencyNotAvailable


lowerCamelCase_								=		{"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase_								=		["DPTFeatureExtractor"]
  lowerCamelCase_								=		["DPTImageProcessor"]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase_								=		[
      "DPT_PRETRAINED_MODEL_ARCHIVE_LIST",
      "DPTForDepthEstimation",
      "DPTForSemanticSegmentation",
      "DPTModel",
      "DPTPreTrainedModel",
  ]


if TYPE_CHECKING:
  from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .feature_extraction_dpt import DPTFeatureExtractor
    from .image_processing_dpt import DPTImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_dpt import (
        DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPTForDepthEstimation,
        DPTForSemanticSegmentation,
        DPTModel,
        DPTPreTrainedModel,
    )


else:
  import sys

  lowerCamelCase_								=		_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)