


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


__snake_case             =   logging.get_logger(__name__)


# General docstring
__snake_case             =   """MobileNetV1Config"""

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

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


__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						(						lowercase  :  List[str]						,							lowercase  :  Dict						,							lowercase  :  Tuple=None			)     ->						Optional[Any]:


				"""simple docstring"""





				snake_case   :				int				 =   {}

				if isinstance(lowercase						,							lowercase			):
								snake_case   :				List[str]				 =   model.mobilenet_va
				else:
								snake_case   :				int				 =   model

				snake_case   :				Any				 =   "MobilenetV1/Conv2d_0/"
				snake_case   :				Optional[Any]				 =   backbone.conv_stem.convolution.weight
				snake_case   :				int				 =   backbone.conv_stem.normalization.bias
				snake_case   :				Union[str, Any]				 =   backbone.conv_stem.normalization.weight
				snake_case   :				Optional[Any]				 =   backbone.conv_stem.normalization.running_mean
				snake_case   :				List[Any]				 =   backbone.conv_stem.normalization.running_var

				for i in range(13			):
								snake_case   :				int				 =   i + 1
								snake_case   :				Dict				 =   i * 2

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

								snake_case   :				int				 =   backbone.layer[pt_index + 1]
								snake_case   :				Any				 =   F'MobilenetV1/Conv2d_{tf_index}_pointwise/'
								snake_case   :				List[str]				 =   pointer.convolution.weight
								snake_case   :				str				 =   pointer.normalization.bias
								snake_case   :				Any				 =   pointer.normalization.weight
								snake_case   :				int				 =   pointer.normalization.running_mean
								snake_case   :				Optional[Any]				 =   pointer.normalization.running_var

				if isinstance(lowercase						,							lowercase			):
								snake_case   :				Dict				 =   "MobilenetV1/Logits/Conv2d_1c_1x1/"
								snake_case   :				Tuple				 =   model.classifier.weight
								snake_case   :				List[Any]				 =   model.classifier.bias

				return tf_to_pt_map







def   __lowerCAmelCase						(						lowercase  :  Dict						,							lowercase  :  Tuple						,							lowercase  :  Optional[Any]			)     ->						List[Any]:


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

				# Build TF to PyTorch weights loading map
				snake_case   :				Dict				 =   _build_tf_to_pytorch_map(lowercase						,							lowercase						,							lowercase			)

				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

								snake_case   :				Union[str, Any]				 =   tf_weights[name]

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

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

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







def   __lowerCAmelCase						(						lowercase  :  torch.Tensor						,							lowercase  :  nn.Convad			)     ->						torch.Tensor:


				"""simple docstring"""





				snake_case   :				Optional[Any]				 =   features.shape[-2:]
				snake_case   :				Any				 =   conv_layer.stride
				snake_case   :				List[str]				 =   conv_layer.kernel_size

				if in_height % stride_height == 0:
								snake_case   :				Union[str, Any]				 =   max(kernel_height - stride_height						,							0			)
				else:
								snake_case   :				Optional[int]				 =   max(kernel_height - (in_height % stride_height)						,							0			)

				if in_width % stride_width == 0:
								snake_case   :				List[str]				 =   max(kernel_width - stride_width						,							0			)
				else:
								snake_case   :				Tuple				 =   max(kernel_width - (in_width % stride_width)						,							0			)

				snake_case   :				Tuple				 =   pad_along_width // 2
				snake_case   :				Optional[Any]				 =   pad_along_width - pad_left
				snake_case   :				Any				 =   pad_along_height // 2
				snake_case   :				Any				 =   pad_along_height - pad_top

				snake_case   :				int				 =   (pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(lowercase						,							lowercase						,							"constant"						,							0.0			)







class _lowerCAmelCase    (				nn.Module     ):







			def __init__(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__ = 1						,     UpperCamelCase__ = 1						,     UpperCamelCase__ = False						,     UpperCamelCase__ = True						,     UpperCamelCase__ = True						,     )     ->		None:

							'''simple docstring'''




							super().__init__()
							snake_case   :				Union[str, Any]				 =   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.'						)

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

							snake_case   :				Dict				 =   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:
											snake_case   :				Any				 =   nn.BatchNormad(
											    num_features=UpperCamelCase__						,     eps=config.layer_norm_eps						,     momentum=0.9997						,     affine=UpperCamelCase__						,     track_running_stats=UpperCamelCase__						,     )
							else:
											snake_case   :				Any				 =   None

							if use_activation:
											if isinstance(UpperCamelCase__						,     UpperCamelCase__						):
															snake_case   :				Optional[Any]				 =   ACTaFN[use_activation]
											elif isinstance(config.hidden_act						,     UpperCamelCase__						):
															snake_case   :				Union[str, Any]				 =   ACTaFN[config.hidden_act]
											else:
															snake_case   :				int				 =   config.hidden_act
							else:
											snake_case   :				List[str]				 =   None







			def 			lowerCamelCase		(     self						,     UpperCamelCase__						)     ->		torch.Tensor:

							'''simple docstring'''




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







class _lowerCAmelCase    (				snake_case_     ):
			__UpperCAmelCase			:	Optional[Any]							  =  MobileNetVaConfig
			__UpperCAmelCase			:	Dict							  =  load_tf_weights_in_mobilenet_va
			__UpperCAmelCase			:	Dict							  =  '''mobilenet_v1'''
			__UpperCAmelCase			:	str							  =  '''pixel_values'''
			__UpperCAmelCase			:	Optional[Any]							  =  False







			def 			lowerCamelCase		(     self						,     UpperCamelCase__						)     ->		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						)



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

__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.'''   ,							snake_case_   ,							)
class _lowerCAmelCase    (				snake_case_     ):







			def __init__(     self						,     UpperCamelCase__						,     UpperCamelCase__ = True						)     ->		Dict:

							'''simple docstring'''




							super().__init__(UpperCamelCase__						)
							snake_case   :				Union[str, Any]				 =   config

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

							snake_case   :				str				 =   MobileNetVaConvLayer(
							    UpperCamelCase__						,     in_channels=config.num_channels						,     out_channels=UpperCamelCase__						,     kernel_size=3						,     stride=2						,     )

							snake_case   :				List[Any]				 =   [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

							snake_case   :				List[Any]				 =   nn.ModuleList()
							for i in range(13						):
											snake_case   :				Any				 =   out_channels

											if strides[i] == 2 or i == 0:
															depth *= 2
															snake_case   :				Any				 =   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						,     )						)

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

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







			def 			lowerCamelCase		(     self						,     UpperCamelCase__						)     ->		Optional[Any]:

							'''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 			lowerCamelCase		(     self						,     UpperCamelCase__ = None						,     UpperCamelCase__ = None						,     UpperCamelCase__ = None						,     )     ->		Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:

							'''simple docstring'''




							snake_case   :				Any				 =   (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							snake_case   :				List[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"						)

							snake_case   :				int				 =   self.conv_stem(UpperCamelCase__						)

							snake_case   :				Dict				 =   () if output_hidden_states else None

							for i, layer_module in enumerate(self.layer						):
											snake_case   :				List[str]				 =   layer_module(UpperCamelCase__						)

											if output_hidden_states:
															snake_case   :				Tuple				 =   all_hidden_states + (hidden_states,)

							snake_case   :				Optional[int]				 =   hidden_states

							if self.pooler is not None:
											snake_case   :				Dict				 =   torch.flatten(self.pooler(UpperCamelCase__						)						,     start_dim=1						)
							else:
											snake_case   :				Any				 =   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.
    '''   ,							snake_case_   ,							)
class _lowerCAmelCase    (				snake_case_     ):







			def __init__(     self						,     UpperCamelCase__						)     ->		None:

							'''simple docstring'''




							super().__init__(UpperCamelCase__						)

							snake_case   :				Union[str, Any]				 =   config.num_labels
							snake_case   :				Optional[int]				 =   MobileNetVaModel(UpperCamelCase__						)

							snake_case   :				List[Any]				 =   self.mobilenet_va.layer[-1].convolution.out_channels

							# Classifier head
							snake_case   :				Union[str, Any]				 =   nn.Dropout(config.classifier_dropout_prob						,     inplace=UpperCamelCase__						)
							snake_case   :				int				 =   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 			lowerCamelCase		(     self						,     UpperCamelCase__ = None						,     UpperCamelCase__ = None						,     UpperCamelCase__ = None						,     UpperCamelCase__ = None						,     )     ->		Union[tuple, ImageClassifierOutputWithNoAttention]:

							'''simple docstring'''




							snake_case   :				Optional[int]				 =   return_dict if return_dict is not None else self.config.use_return_dict

							snake_case   :				Optional[Any]				 =   self.mobilenet_va(UpperCamelCase__						,     output_hidden_states=UpperCamelCase__						,     return_dict=UpperCamelCase__						)

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

							snake_case   :				Optional[Any]				 =   self.classifier(self.dropout(UpperCamelCase__						)						)

							snake_case   :				List[Any]				 =   None
							if labels is not None:
											if self.config.problem_type is None:
															if self.num_labels == 1:
																			snake_case   :				Union[str, Any]				 =   "regression"
															elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																			snake_case   :				Any				 =   "single_label_classification"
															else:
																			snake_case   :				List[str]				 =   "multi_label_classification"

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

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

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









"""simple docstring"""



from typing import TYPE_CHECKING

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


__snake_case             =   {
    """configuration_conditional_detr""": [
        """CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """ConditionalDetrConfig""",
        """ConditionalDetrOnnxConfig""",
    ]
}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __snake_case             =   ["""ConditionalDetrFeatureExtractor"""]
  __snake_case             =   ["""ConditionalDetrImageProcessor"""]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __snake_case             =   [
      """CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """ConditionalDetrForObjectDetection""",
      """ConditionalDetrForSegmentation""",
      """ConditionalDetrModel""",
      """ConditionalDetrPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_conditional_detr import (
      CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP,
      ConditionalDetrConfig,
      ConditionalDetrOnnxConfig,
  )

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor
    from .image_processing_conditional_detr import ConditionalDetrImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_conditional_detr import (
        CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
        ConditionalDetrForObjectDetection,
        ConditionalDetrForSegmentation,
        ConditionalDetrModel,
        ConditionalDetrPreTrainedModel,
    )

else:
  import sys

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





