
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


UpperCamelCase_						=						logging.get_logger(__name__)


# General docstring
UpperCamelCase_						=						"""MobileNetV1Config"""

# Base docstring
UpperCamelCase_						=						"""google/mobilenet_v1_1.0_224"""
UpperCamelCase_						=						[1, 10_24, 7, 7]

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


UpperCamelCase_						=						[
    """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      (       lowerCamelCase_:	Union[str, Any]					,						lowerCamelCase_:	Optional[Any]					,						lowerCamelCase_:	Any=None		):



				'''simple docstring'''







				A  :	Union[str, Any]				=					{}

				if isinstance(lowerCamelCase_					,						lowerCamelCase_		):
								A  :	List[str]				=					model.mobilenet_va
				else:
								A  :	Dict				=					model

				A  :	Any				=					"MobilenetV1/Conv2d_0/"
				A  :	Tuple				=					backbone.conv_stem.convolution.weight
				A  :	List[Any]				=					backbone.conv_stem.normalization.bias
				A  :	str				=					backbone.conv_stem.normalization.weight
				A  :	List[Any]				=					backbone.conv_stem.normalization.running_mean
				A  :	Dict				=					backbone.conv_stem.normalization.running_var

				for i in range(13		):
								A  :	str				=					i + 1
								A  :	Dict				=					i * 2

								A  :	int				=					backbone.layer[pt_index]
								A  :	int				=					f"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
								A  :	List[Any]				=					pointer.convolution.weight
								A  :	Optional[Any]				=					pointer.normalization.bias
								A  :	List[str]				=					pointer.normalization.weight
								A  :	int				=					pointer.normalization.running_mean
								A  :	Tuple				=					pointer.normalization.running_var

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

				if isinstance(lowerCamelCase_					,						lowerCamelCase_		):
								A  :	str				=					"MobilenetV1/Logits/Conv2d_1c_1x1/"
								A  :	Optional[Any]				=					model.classifier.weight
								A  :	str				=					model.classifier.bias

				return tf_to_pt_map





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

				# Build TF to PyTorch weights loading map
				A  :	Dict				=					_build_tf_to_pytorch_map(lowerCamelCase_					,						lowerCamelCase_					,						lowerCamelCase_		)

				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

								A  :	Optional[Any]				=					tf_weights[name]

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

								tf_weights.pop(lowerCamelCase_					,						lowerCamelCase_		)
								tf_weights.pop(name + '''/RMSProp'''					,						lowerCamelCase_		)
								tf_weights.pop(name + '''/RMSProp_1'''					,						lowerCamelCase_		)
								tf_weights.pop(name + '''/ExponentialMovingAverage'''					,						lowerCamelCase_		)

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





def 				_lowerCamelCase      (       lowerCamelCase_:	Optional[int]					,						lowerCamelCase_:	Any		):



				'''simple docstring'''







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

				if in_height % stride_height == 0:
								A  :	Tuple				=					max(kernel_height - stride_height					,						0		)
				else:
								A  :	List[Any]				=					max(kernel_height - (in_height % stride_height)					,						0		)

				if in_width % stride_width == 0:
								A  :	str				=					max(kernel_width - stride_width					,						0		)
				else:
								A  :	Tuple				=					max(kernel_width - (in_width % stride_width)					,						0		)

				A  :	Any				=					pad_along_width // 2
				A  :	Tuple				=					pad_along_width - pad_left
				A  :	Dict				=					pad_along_height // 2
				A  :	Any				=					pad_along_height - pad_top

				A  :	Optional[Any]				=					(pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(lowerCamelCase_					,						lowerCamelCase_					,						'''constant'''					,						0.0		)

class      _SCREAMING_SNAKE_CASE				(		nn.Module				):





				def __init__(		self			:		Any       ,   snake_case_			:		Dict       ,   snake_case_			:		Tuple       ,   snake_case_			:		List[Any]       ,   snake_case_			:		Any       ,   snake_case_			:		str = 1       ,   snake_case_			:		Optional[int] = 1       ,   snake_case_			:		Optional[int] = False       ,   snake_case_			:		Tuple = True       ,   snake_case_			:		Any = True       ,   ):


								"""simple docstring"""

								super().__init__()
								A  :	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."""				)

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

								A  :	List[Any]				=					nn.Convad(
								    in_channels=snake_case_       ,   out_channels=snake_case_       ,   kernel_size=snake_case_       ,   stride=snake_case_       ,   padding=snake_case_       ,   groups=snake_case_       ,   bias=snake_case_       ,   padding_mode='''zeros'''       ,   )

								if use_normalization:
												A  :	Optional[int]				=					nn.BatchNormad(
												    num_features=snake_case_       ,   eps=config.layer_norm_eps       ,   momentum=0.99_97       ,   affine=snake_case_       ,   track_running_stats=snake_case_       ,   )
								else:
												A  :	Union[str, Any]				=					None

								if use_activation:
												if isinstance(snake_case_       ,   snake_case_				):
																A  :	Any				=					ACTaFN[use_activation]
												elif isinstance(config.hidden_act       ,   snake_case_				):
																A  :	List[Any]				=					ACTaFN[config.hidden_act]
												else:
																A  :	Any				=					config.hidden_act
								else:
												A  :	Any				=					None






				def 							_UpperCAmelCase    (		self			:		List[Any]       ,   snake_case_			:		Any				):


								"""simple docstring"""

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



class      _SCREAMING_SNAKE_CASE				(		_UpperCamelCase				):
				lowerCamelCase_	  =  MobileNetVaConfig
				lowerCamelCase_	  =  load_tf_weights_in_mobilenet_va
				lowerCamelCase_	  =  """mobilenet_v1"""
				lowerCamelCase_	  =  """pixel_values"""
				lowerCamelCase_	  =  False





				def 							_UpperCAmelCase    (		self			:		Tuple       ,   snake_case_			:		str				):


								"""simple docstring"""

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



UpperCamelCase_						=						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.
"""

UpperCamelCase_						=						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.',     _UpperCamelCase,     )
class      _SCREAMING_SNAKE_CASE				(		_UpperCamelCase				):





				def __init__(		self			:		Any       ,   snake_case_			:		Any       ,   snake_case_			:		Any = True				):


								"""simple docstring"""

								super().__init__(snake_case_				)
								A  :	Dict				=					config

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

								A  :	Optional[Any]				=					MobileNetVaConvLayer(
								    snake_case_       ,   in_channels=config.num_channels       ,   out_channels=snake_case_       ,   kernel_size=3       ,   stride=2       ,   )

								A  :	List[str]				=					[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

								A  :	str				=					nn.ModuleList()
								for i in range(13				):
												A  :	Any				=					out_channels

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

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

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

								A  :	Tuple				=					nn.AdaptiveAvgPoolad((1, 1)				) if add_pooling_layer else None

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





				def 							_UpperCAmelCase    (		self			:		Dict       ,   snake_case_			:		Optional[Any]				):


								"""simple docstring"""

								raise NotImplementedError






				@add_start_docstrings_to_model_forward(snake_case_				)
				@add_code_sample_docstrings(
				    checkpoint=_CHECKPOINT_FOR_DOC       ,   output_type=snake_case_       ,   config_class=_CONFIG_FOR_DOC       ,   modality='''vision'''       ,   expected_output=_EXPECTED_OUTPUT_SHAPE       ,   )
				def 							_UpperCAmelCase    (		self			:		Tuple       ,   snake_case_			:		Optional[int] = None       ,   snake_case_			:		Union[str, Any] = None       ,   snake_case_			:		List[str] = None       ,   ):


								"""simple docstring"""

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

								A  :	List[str]				=					self.conv_stem(snake_case_				)

								A  :	Optional[Any]				=					() if output_hidden_states else None

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

												if output_hidden_states:
																A  :	Dict				=					all_hidden_states + (hidden_states,)

								A  :	Any				=					hidden_states

								if self.pooler is not None:
												A  :	List[Any]				=					torch.flatten(self.pooler(snake_case_				)       ,   start_dim=1				)
								else:
												A  :	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=snake_case_       ,   pooler_output=snake_case_       ,   hidden_states=snake_case_       ,   )



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





				def __init__(		self			:		List[Any]       ,   snake_case_			:		Tuple				):


								"""simple docstring"""

								super().__init__(snake_case_				)

								A  :	Tuple				=					config.num_labels
								A  :	Optional[Any]				=					MobileNetVaModel(snake_case_				)

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

								# Classifier head
								A  :	Any				=					nn.Dropout(config.classifier_dropout_prob       ,   inplace=snake_case_				)
								A  :	Optional[int]				=					nn.Linear(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(snake_case_				)
				@add_code_sample_docstrings(
				    checkpoint=_IMAGE_CLASS_CHECKPOINT       ,   output_type=snake_case_       ,   config_class=_CONFIG_FOR_DOC       ,   expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT       ,   )
				def 							_UpperCAmelCase    (		self			:		List[Any]       ,   snake_case_			:		Tuple = None       ,   snake_case_			:		Dict = None       ,   snake_case_			:		Optional[int] = None       ,   snake_case_			:		int = None       ,   ):


								"""simple docstring"""

								A  :	List[str]				=					return_dict if return_dict is not None else self.config.use_return_dict

								A  :	List[str]				=					self.mobilenet_va(snake_case_       ,   output_hidden_states=snake_case_       ,   return_dict=snake_case_				)

								A  :	int				=					outputs.pooler_output if return_dict else outputs[1]

								A  :	Dict				=					self.classifier(self.dropout(snake_case_				)				)

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

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

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

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






from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    {
    """configuration_autoformer""": [
        """AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """AutoformerConfig""",
    ],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  SCREAMING_SNAKE_CASE__							:      Tuple         =    [
      """AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """AutoformerForPrediction""",
      """AutoformerModel""",
      """AutoformerPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_autoformer import (
      AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
      AutoformerConfig,
  )

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_autoformer import (
        AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
        AutoformerForPrediction,
        AutoformerModel,
        AutoformerPreTrainedModel,
    )

else:
  import sys

  SCREAMING_SNAKE_CASE__							:      Any         =    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

