



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


__lowerCAmelCase       :					Optional[Any]      					=					logging.get_logger(__name__)


# General docstring
__lowerCAmelCase       :					List[str]      					=					'''MobileNetV1Config'''

# Base docstring
__lowerCAmelCase       :					Union[str, Any]      					=					'''google/mobilenet_v1_1.0_224'''
__lowerCAmelCase       :					int      					=					[1, 1024, 7, 7]

# Image classification docstring
__lowerCAmelCase       :					Union[str, Any]      					=					'''google/mobilenet_v1_1.0_224'''
__lowerCAmelCase       :					Dict      					=					'''tabby, tabby cat'''


__lowerCAmelCase       :					List[str]      					=					[
    '''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      :			List[Any]					, __UpperCamelCase      :			Optional[int]					, __UpperCamelCase      :			Union[str, Any]=None    ):


						'''simple docstring'''






						snake_case_   : Tuple						=			{}

						if isinstance(__UpperCamelCase					, __UpperCamelCase    ):
												snake_case_   : List[Any]						=			model.mobilenet_va
						else:
												snake_case_   : Union[str, Any]						=			model

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

						for i in range(1_3    ):
												snake_case_   : List[str]						=			i + 1
												snake_case_   : Optional[int]						=			i * 2

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

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

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

						return tf_to_pt_map
def 	__lowerCAmelCase						(		__UpperCamelCase      :			List[str]					, __UpperCamelCase      :			Any					, __UpperCamelCase      :			Union[str, 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_   : Optional[int]						=			tf.train.list_variables(__UpperCamelCase    )
						snake_case_   : Dict						=			{}
						for name, shape in init_vars:
												logger.info(F'Loading TF weight {name} with shape {shape}'    )
												snake_case_   : Any						=			tf.train.load_variable(__UpperCamelCase					, __UpperCamelCase    )
												snake_case_   : str						=			array

						# Build TF to PyTorch weights loading map
						snake_case_   : str						=			_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

												snake_case_   : Dict						=			tf_weights[name]

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


						'''simple docstring'''






						snake_case_			,		snake_case_   : Optional[int]						=			features.shape[-2:]
						snake_case_			,		snake_case_   : int						=			conv_layer.stride
						snake_case_			,		snake_case_   : Dict						=			conv_layer.kernel_size

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

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

						snake_case_   : int						=			pad_along_width // 2
						snake_case_   : Optional[Any]						=			pad_along_width - pad_left
						snake_case_   : Any						=			pad_along_height // 2
						snake_case_   : List[str]						=			pad_along_height - pad_top

						snake_case_   : Dict						=			(pad_left, pad_right, pad_top, pad_bottom)
						return nn.functional.pad(__UpperCamelCase					, __UpperCamelCase					, """constant"""					, 0.0    )



class    _lowerCAmelCase    (				nn.Module		):





		"""simple docstring"""






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







								'''simple docstring'''

								super().__init__()
								snake_case_   : Optional[int]						=			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_   : Dict						=			0 if config.tf_padding else int((kernel_size - 1) / 2   )

								snake_case_   : Dict						=			nn.Convad(
								    in_channels=_lowercase							,    out_channels=_lowercase							,    kernel_size=_lowercase							,    stride=_lowercase							,    padding=_lowercase							,    groups=_lowercase							,    bias=_lowercase							,    padding_mode="""zeros"""							,    )

								if use_normalization:
														snake_case_   : Tuple						=			nn.BatchNormad(
														    num_features=_lowercase							,    eps=config.layer_norm_eps							,    momentum=0.9997							,    affine=_lowercase							,    track_running_stats=_lowercase							,    )
								else:
														snake_case_   : Union[str, Any]						=			None

								if use_activation:
														if isinstance(_lowercase							,    _lowercase   ):
																				snake_case_   : str						=			ACTaFN[use_activation]
														elif isinstance(config.hidden_act							,    _lowercase   ):
																				snake_case_   : Optional[int]						=			ACTaFN[config.hidden_act]
														else:
																				snake_case_   : Union[str, Any]						=			config.hidden_act
								else:
														snake_case_   : Tuple						=			None





		def    UpperCAmelCase__							(					self							,    _lowercase   ) ->						torch.Tensor:







								'''simple docstring'''

								if self.config.tf_padding:
														snake_case_   : Dict						=			apply_tf_padding(_lowercase							,    self.convolution   )
								snake_case_   : str						=			self.convolution(_lowercase   )
								if self.normalization is not None:
														snake_case_   : List[str]						=			self.normalization(_lowercase   )
								if self.activation is not None:
														snake_case_   : List[Any]						=			self.activation(_lowercase   )
								return features




class    _lowerCAmelCase    (				SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		_lowerCamelCase			  =       MobileNetVaConfig
		_lowerCamelCase			  =       load_tf_weights_in_mobilenet_va
		_lowerCamelCase			  =       '''mobilenet_v1'''
		_lowerCamelCase			  =       '''pixel_values'''
		_lowerCamelCase			  =       False





		def    UpperCAmelCase__							(					self							,    _lowercase   ) ->						None:







								'''simple docstring'''

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




__lowerCAmelCase       :					List[str]      					=					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.
'''

__lowerCAmelCase       :					Optional[Any]      					=					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.'''  ,				SCREAMING_SNAKE_CASE__  ,				)
class    _lowerCAmelCase    (				SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		def __init__(					self							,    _lowercase							,    _lowercase = True   ) ->						Tuple:







								'''simple docstring'''

								super().__init__(_lowercase   )
								snake_case_   : str						=			config

								snake_case_   : int						=			3_2
								snake_case_   : str						=			max(int(depth * config.depth_multiplier   )							,    config.min_depth   )

								snake_case_   : Union[str, Any]						=			MobileNetVaConvLayer(
								    _lowercase							,    in_channels=config.num_channels							,    out_channels=_lowercase							,    kernel_size=3							,    stride=2							,    )

								snake_case_   : Tuple						=			[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

								snake_case_   : Union[str, Any]						=			nn.ModuleList()
								for i in range(1_3   ):
														snake_case_   : Optional[Any]						=			out_channels

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

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

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

								snake_case_   : Optional[int]						=			nn.AdaptiveAvgPoolad((1, 1)   ) if add_pooling_layer else None

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





		def    UpperCAmelCase__							(					self							,    _lowercase   ) ->						Optional[Any]:







								'''simple docstring'''

								raise NotImplementedError





		@add_start_docstrings_to_model_forward(_lowercase   )
		@add_code_sample_docstrings(
		    checkpoint=_CHECKPOINT_FOR_DOC							,    output_type=_lowercase							,    config_class=_CONFIG_FOR_DOC							,    modality="""vision"""							,    expected_output=_EXPECTED_OUTPUT_SHAPE							,    )
		def    UpperCAmelCase__							(					self							,    _lowercase = None							,    _lowercase = None							,    _lowercase = None							,    ) ->						Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:







								'''simple docstring'''

								snake_case_   : Tuple						=			(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								snake_case_   : int						=			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_   : List[Any]						=			self.conv_stem(_lowercase   )

								snake_case_   : Union[str, Any]						=			() if output_hidden_states else None

								for i, layer_module in enumerate(self.layer   ):
														snake_case_   : int						=			layer_module(_lowercase   )

														if output_hidden_states:
																				snake_case_   : Optional[Any]						=			all_hidden_states + (hidden_states,)

								snake_case_   : Tuple						=			hidden_states

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




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





		"""simple docstring"""






		def __init__(					self							,    _lowercase   ) ->						None:







								'''simple docstring'''

								super().__init__(_lowercase   )

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

								snake_case_   : List[str]						=			self.mobilenet_va.layer[-1].convolution.out_channels

								# Classifier head
								snake_case_   : str						=			nn.Dropout(config.classifier_dropout_prob							,    inplace=_lowercase   )
								snake_case_   : List[str]						=			nn.Linear(_lowercase							,    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(_lowercase   )
		@add_code_sample_docstrings(
		    checkpoint=_IMAGE_CLASS_CHECKPOINT							,    output_type=_lowercase							,    config_class=_CONFIG_FOR_DOC							,    expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT							,    )
		def    UpperCAmelCase__							(					self							,    _lowercase = None							,    _lowercase = None							,    _lowercase = None							,    _lowercase = None							,    ) ->						Union[tuple, ImageClassifierOutputWithNoAttention]:







								'''simple docstring'''

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

								snake_case_   : Dict						=			self.mobilenet_va(_lowercase							,    output_hidden_states=_lowercase							,    return_dict=_lowercase   )

								snake_case_   : str						=			outputs.pooler_output if return_dict else outputs[1]

								snake_case_   : Optional[int]						=			self.classifier(self.dropout(_lowercase   )   )

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

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

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

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






"""simple docstring"""





def 	__lowerCAmelCase						(		__UpperCamelCase      :			str    ):


						'''simple docstring'''






						return " ".join(input_str.split()[::-1]    )


if __name__ == "__main__":
					import doctest

					doctest.testmod()

