





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_		:				List[Any]				=						logging.get_logger(__name__)


# General docstring
lowercase_		:				Tuple				=						'''MobileNetV1Config'''

# Base docstring
lowercase_		:				Any				=						'''google/mobilenet_v1_1.0_224'''
lowercase_		:				Any				=						[1, 1024, 7, 7]

# Image classification docstring
lowercase_		:				Optional[int]				=						'''google/mobilenet_v1_1.0_224'''
lowercase_		:				Dict				=						'''tabby, tabby cat'''


lowercase_		:				Optional[int]				=						[
    '''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       A__(		__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase=None ):
				_snake_case :			List[Any]  						=   {}

				if isinstance(__lowerCAmelCase	,			__lowerCAmelCase ):
								_snake_case :			Dict  						=   model.mobilenet_va
				else:
								_snake_case :			Tuple  						=   model

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

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

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

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

				if isinstance(__lowerCAmelCase	,			__lowerCAmelCase ):
								_snake_case :			Tuple  						=   'MobilenetV1/Logits/Conv2d_1c_1x1/'
								_snake_case :			Any  						=   model.classifier.weight
								_snake_case :			Union[str, Any]  						=   model.classifier.bias

				return tf_to_pt_map

def       A__(		__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase ):
				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 :			Tuple  						=   tf.train.list_variables(__lowerCAmelCase )
				_snake_case :			List[str]  						=   {}
				for name, shape in init_vars:
								logger.info(F'''Loading TF weight {name} with shape {shape}''' )
								_snake_case :			Any  						=   tf.train.load_variable(__lowerCAmelCase	,			__lowerCAmelCase )
								_snake_case :			Tuple  						=   array

				# Build TF to PyTorch weights loading map
				_snake_case :			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

								_snake_case :			int  						=   tf_weights[name]

								if "depthwise_weights" in name:
												logger.info('Transposing depthwise' )
												_snake_case :			int  						=   np.transpose(__lowerCAmelCase	,			(2, 3, 0, 1) )
								elif "weights" in name:
												logger.info('Transposing' )
												if len(pointer.shape ) == 2:  # copying into linear layer
																_snake_case :			int  						=   array.squeeze().transpose()
												else:
																_snake_case :			Tuple  						=   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}''' )
								_snake_case :			str  						=   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       A__(		__lowerCAmelCase	,			__lowerCAmelCase ):
				_snake_case						,			_snake_case :			Any  						=   features.shape[-2:]
				_snake_case						,			_snake_case :			Optional[Any]  						=   conv_layer.stride
				_snake_case						,			_snake_case :			Optional[Any]  						=   conv_layer.kernel_size

				if in_height % stride_height == 0:
								_snake_case :			Any  						=   max(kernel_height - stride_height	,			0 )
				else:
								_snake_case :			List[str]  						=   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 :			Union[str, Any]  						=   max(kernel_width - (in_width % stride_width)	,			0 )

				_snake_case :			Tuple  						=   pad_along_width // 2
				_snake_case :			Any  						=   pad_along_width - pad_left
				_snake_case :			Union[str, Any]  						=   pad_along_height // 2
				_snake_case :			Optional[int]  						=   pad_along_height - pad_top

				_snake_case :			List[Any]  						=   (pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(__lowerCAmelCase	,			__lowerCAmelCase	,			'constant'	,			0.0 )


class 			lowercase				(							nn.Module     ):



						"""simple docstring"""

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





										'''simple docstring'''







										super().__init__()
										_snake_case :			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.'''					)

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

										_snake_case :			str  						=   nn.Convad(
										    in_channels=lowerCamelCase_ ,				out_channels=lowerCamelCase_ ,				kernel_size=lowerCamelCase_ ,				stride=lowerCamelCase_ ,				padding=lowerCamelCase_ ,				groups=lowerCamelCase_ ,				bias=lowerCamelCase_ ,				padding_mode='zeros' ,				)

										if use_normalization:
														_snake_case :			List[Any]  						=   nn.BatchNormad(
														    num_features=lowerCamelCase_ ,				eps=config.layer_norm_eps ,				momentum=0.9997 ,				affine=lowerCamelCase_ ,				track_running_stats=lowerCamelCase_ ,				)
										else:
														_snake_case :			Any  						=   None

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







						def 		__UpperCAmelCase       (    self			:		Tuple ,				lowerCamelCase_			:		torch.Tensor					):





										'''simple docstring'''







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



class 			lowercase				(							a_     ):



						"""simple docstring"""

						_UpperCamelCase  :	str								=	MobileNetVaConfig
						_UpperCamelCase  :	Union[str, Any]								=	load_tf_weights_in_mobilenet_va
						_UpperCamelCase  :	int								=	"mobilenet_v1"
						_UpperCamelCase  :	str								=	"pixel_values"
						_UpperCamelCase  :	Optional[Any]								=	False







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





										'''simple docstring'''







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



lowercase_		:				Optional[Any]				=						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.
'''

lowercase_		:				Optional[int]				=						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."		,			a_		,			)
class 			lowercase				(							a_     ):



						"""simple docstring"""

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





										'''simple docstring'''







										super().__init__(lowerCamelCase_					)
										_snake_case :			int  						=   config

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

										_snake_case :			List[str]  						=   MobileNetVaConvLayer(
										    lowerCamelCase_ ,				in_channels=config.num_channels ,				out_channels=lowerCamelCase_ ,				kernel_size=3 ,				stride=2 ,				)

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

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

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

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

														self.layer.append(
														    MobileNetVaConvLayer(
														        lowerCamelCase_ ,				in_channels=lowerCamelCase_ ,				out_channels=lowerCamelCase_ ,				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			:		str ,				lowerCamelCase_			:		Tuple					):





										'''simple docstring'''







										raise NotImplementedError







						@add_start_docstrings_to_model_forward(lowerCamelCase_					)
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC ,				output_type=lowerCamelCase_ ,				config_class=_CONFIG_FOR_DOC ,				modality='vision' ,				expected_output=_EXPECTED_OUTPUT_SHAPE ,				)
						def 		__UpperCAmelCase       (    self			:		Union[str, Any] ,				lowerCamelCase_			:		Optional[torch.Tensor] = None ,				lowerCamelCase_			:		Optional[bool] = None ,				lowerCamelCase_			:		Optional[bool] = None ,				):





										'''simple docstring'''







										_snake_case :			Dict  						=   (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										_snake_case :			List[str]  						=   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 :			Optional[int]  						=   self.conv_stem(lowerCamelCase_					)

										_snake_case :			Dict  						=   () if output_hidden_states else None

										for i, layer_module in enumerate(self.layer					):
														_snake_case :			Optional[int]  						=   layer_module(lowerCamelCase_					)

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

										_snake_case :			List[Any]  						=   hidden_states

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



@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    "		,			a_		,			)
class 			lowercase				(							a_     ):



						"""simple docstring"""

						def __init__(    self			:		List[Any] ,				lowerCamelCase_			:		MobileNetVaConfig					):





										'''simple docstring'''







										super().__init__(lowerCamelCase_					)

										_snake_case :			int  						=   config.num_labels
										_snake_case :			Any  						=   MobileNetVaModel(lowerCamelCase_					)

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

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





										'''simple docstring'''







										_snake_case :			str  						=   return_dict if return_dict is not None else self.config.use_return_dict

										_snake_case :			int  						=   self.mobilenet_va(lowerCamelCase_ ,				output_hidden_states=lowerCamelCase_ ,				return_dict=lowerCamelCase_					)

										_snake_case :			List[Any]  						=   outputs.pooler_output if return_dict else outputs[1]

										_snake_case :			Union[str, Any]  						=   self.classifier(self.dropout(lowerCamelCase_					)					)

										_snake_case :			Optional[int]  						=   None
										if labels is not None:
														if self.config.problem_type is None:
																		if self.num_labels == 1:
																						_snake_case :			Optional[int]  						=   '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 :			Tuple  						=   'multi_label_classification'

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

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

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













import torch

from transformers import AutoModel


class 			lowercase				(							torch.nn.Module     ):



						"""simple docstring"""

						def __init__(    self			:		Tuple ,				lowerCamelCase_			:		Dict="sayef/fsner-bert-base-uncased"					):





										'''simple docstring'''







										super(lowerCamelCase_ ,				self					).__init__()

										_snake_case :			Optional[Any]  						=   AutoModel.from_pretrained(lowerCamelCase_ ,				return_dict=lowerCamelCase_					)
										_snake_case :			str  						=   torch.nn.CosineSimilarity(3 ,				1e-08					)
										_snake_case :			str  						=   torch.nn.Softmax(dim=1					)







						def 		__UpperCAmelCase       (    self			:		int ,				**lowerCamelCase_			:		List[str]					):





										'''simple docstring'''







										return self.bert(**lowerCamelCase_					).last_hidden_state







						def 		__UpperCAmelCase       (    self			:		List[Any] ,				lowerCamelCase_			:		Union[str, Any]					):





										'''simple docstring'''







										return token_embeddings.sum(2 ,				keepdim=lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		Dict ,				lowerCamelCase_			:		Dict ,				lowerCamelCase_			:		Tuple ,				lowerCamelCase_			:		Optional[Any]=1					):





										'''simple docstring'''







										return self.softmax(T * self.cos(lowerCamelCase_ ,				lowerCamelCase_					)					)







						def 		__UpperCAmelCase       (    self			:		Optional[Any] ,				lowerCamelCase_			:		Any ,				lowerCamelCase_			:		Union[str, Any]					):





										'''simple docstring'''







										_snake_case :			int  						=   W_supports['sizes'].tolist()
										_snake_case :			int  						=   W_supports['start_token_id'].item()
										_snake_case :			List[str]  						=   W_supports['end_token_id'].item()

										del W_supports["sizes"]
										del W_supports["start_token_id"]
										del W_supports["end_token_id"]

										_snake_case :			Optional[int]  						=   self.BERT(**lowerCamelCase_					)
										_snake_case :			Optional[Any]  						=   self.BERT(**lowerCamelCase_					)

										_snake_case :			Optional[int]  						=   None
										_snake_case :			Optional[int]  						=   None

										_snake_case :			List[str]  						=   W_supports['input_ids'] == start_token_id
										_snake_case :			Union[str, Any]  						=   W_supports['input_ids'] == end_token_id

										for i, size in enumerate(lowerCamelCase_					):
														if i == 0:
																		_snake_case :			str  						=   0
														else:
																		_snake_case :			Union[str, Any]  						=   support_sizes[i - 1]

														_snake_case :			Tuple  						=   S[s : s + size][start_token_masks[s : s + size]]
														_snake_case :			Optional[int]  						=   S[s : s + size][end_token_masks[s : s + size]]

														_snake_case :			Tuple  						=   torch.matmul(q[i] ,				s_start.T					).sum(1					).softmax(0					)
														_snake_case :			Union[str, Any]  						=   torch.matmul(q[i] ,				s_end.T					).sum(1					).softmax(0					)

														if p_starts is not None:
																		_snake_case :			Optional[Any]  						=   torch.vstack((p_starts, p_start)					)
																		_snake_case :			List[str]  						=   torch.vstack((p_ends, p_end)					)
														else:
																		_snake_case :			Union[str, Any]  						=   p_start
																		_snake_case :			Any  						=   p_end

										return p_starts, p_ends






