


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, 1_024, 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 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		Any       ,  SCREAMING_SNAKE_CASE_   :		List[Any]       ,  SCREAMING_SNAKE_CASE_   :		Union[str, Any]=None	):





			"""simple docstring"""




			UpperCamelCase         =					{}

			if isinstance(SCREAMING_SNAKE_CASE_       ,  SCREAMING_SNAKE_CASE_	):
						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(SCREAMING_SNAKE_CASE_       ,  SCREAMING_SNAKE_CASE_	):
						UpperCamelCase         =					"""MobilenetV1/Logits/Conv2d_1c_1x1/"""
						UpperCamelCase         =					model.classifier.weight
						UpperCamelCase         =					model.classifier.bias

			return tf_to_pt_map






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

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

			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(SCREAMING_SNAKE_CASE_       ,  (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(SCREAMING_SNAKE_CASE_       ,  (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(SCREAMING_SNAKE_CASE_	)

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

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






def 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		torch.Tensor       ,  SCREAMING_SNAKE_CASE_   :		nn.Convad	):





			"""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(SCREAMING_SNAKE_CASE_       ,  SCREAMING_SNAKE_CASE_       ,  """constant"""       ,  0.0	)




class    UpperCAmelCase					(       nn.Module    ):

			'''simple docstring'''





			def __init__(						self							:		str       ,       __magic_name__							:		MobileNetVaConfig       ,       __magic_name__							:		int       ,       __magic_name__							:		int       ,       __magic_name__							:		int       ,       __magic_name__							:		Optional[int] = 1       ,       __magic_name__							:		Optional[int] = 1       ,       __magic_name__							:		bool = False       ,       __magic_name__							:		Optional[bool] = True       ,       __magic_name__							:		Optional[bool or str] = True       ,       ):







						"""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=__magic_name__       ,       out_channels=__magic_name__       ,       kernel_size=__magic_name__       ,       stride=__magic_name__       ,       padding=__magic_name__       ,       groups=__magic_name__       ,       bias=__magic_name__       ,       padding_mode="""zeros"""       ,       )

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

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





			def   lowerCamelCase_					(						self							:		Any       ,       __magic_name__							:		torch.Tensor						):







						"""simple docstring"""







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




class    UpperCAmelCase					(       __snake_case    ):

			'''simple docstring'''





			lowercase						= MobileNetVaConfig
			lowercase						= load_tf_weights_in_mobilenet_va
			lowercase						= """mobilenet_v1"""
			lowercase						= """pixel_values"""
			lowercase						= False




			def   lowerCamelCase_					(						self							:		Any       ,       __magic_name__							:		Union[nn.Linear, nn.Convad]						):







						"""simple docstring"""







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


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

__snake_case            =   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."""      , __snake_case      , )
class    UpperCAmelCase					(       __snake_case    ):

			'''simple docstring'''





			def __init__(						self							:		str       ,       __magic_name__							:		MobileNetVaConfig       ,       __magic_name__							:		bool = True						):







						"""simple docstring"""







						super().__init__(__magic_name__						)
						UpperCamelCase         =					config

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

						UpperCamelCase         =					MobileNetVaConvLayer(
						    __magic_name__       ,       in_channels=config.num_channels       ,       out_channels=__magic_name__       ,       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(1_3						):
									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(
									        __magic_name__       ,       in_channels=__magic_name__       ,       out_channels=__magic_name__       ,       kernel_size=3       ,       stride=strides[i]       ,       groups=__magic_name__       ,       )						)

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

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

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




			def   lowerCamelCase_					(						self							:		Union[str, Any]       ,       __magic_name__							:		Tuple						):







						"""simple docstring"""







						raise NotImplementedError





			@add_start_docstrings_to_model_forward(__magic_name__						)
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC       ,       output_type=__magic_name__       ,       config_class=_CONFIG_FOR_DOC       ,       modality="""vision"""       ,       expected_output=_EXPECTED_OUTPUT_SHAPE       ,       )
			def   lowerCamelCase_					(						self							:		Optional[int]       ,       __magic_name__							:		Optional[torch.Tensor] = None       ,       __magic_name__							:		Optional[bool] = None       ,       __magic_name__							:		Optional[bool] = None       ,       ):







						"""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(__magic_name__						)

						UpperCamelCase         =					() if output_hidden_states else None

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

									if output_hidden_states:
												UpperCamelCase         =					all_hidden_states + (hidden_states,)

						UpperCamelCase         =					hidden_states

						if self.pooler is not None:
									UpperCamelCase         =					torch.flatten(self.pooler(__magic_name__						)       ,       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=__magic_name__       ,       pooler_output=__magic_name__       ,       hidden_states=__magic_name__       ,       )




@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    UpperCAmelCase					(       __snake_case    ):

			'''simple docstring'''





			def __init__(						self							:		Tuple       ,       __magic_name__							:		MobileNetVaConfig						):







						"""simple docstring"""







						super().__init__(__magic_name__						)

						UpperCamelCase         =					config.num_labels
						UpperCamelCase         =					MobileNetVaModel(__magic_name__						)

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

						# Classifier head
						UpperCamelCase         =					nn.Dropout(config.classifier_dropout_prob       ,       inplace=__magic_name__						)
						UpperCamelCase         =					nn.Linear(__magic_name__       ,       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(__magic_name__						)
			@add_code_sample_docstrings(
			    checkpoint=_IMAGE_CLASS_CHECKPOINT       ,       output_type=__magic_name__       ,       config_class=_CONFIG_FOR_DOC       ,       expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT       ,       )
			def   lowerCamelCase_					(						self							:		int       ,       __magic_name__							:		Optional[torch.Tensor] = None       ,       __magic_name__							:		Optional[bool] = None       ,       __magic_name__							:		Optional[torch.Tensor] = None       ,       __magic_name__							:		Optional[bool] = None       ,       ):







						"""simple docstring"""







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

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

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

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

						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(__magic_name__       ,       __magic_name__						)
									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(__magic_name__       ,       __magic_name__						)

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

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








from ..utils import DummyObject, requires_backends




class    UpperCAmelCase					(       metaclass=__snake_case    ):
			lowercase						= ["""keras_nlp"""]




			def __init__(						self							:		List[str]       ,       *__magic_name__							:		str       ,       **__magic_name__							:		int						):







						"""simple docstring"""







						requires_backends(self       ,       ["""keras_nlp"""]						)




