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


A_    							=					logging.get_logger(__name__)


# General docstring
A_    							=					"MobileNetV1Config"

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

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


A_    							=					[
    "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						(	lowerCAmelCase__	,lowerCAmelCase__	,lowerCAmelCase__=None						):
			lowerCamelCase_					=  {}

			if isinstance(lowerCAmelCase__	,lowerCAmelCase__						):
						lowerCamelCase_					=  model.mobilenet_va
			else:
						lowerCamelCase_					=  model

			lowerCamelCase_					=  """MobilenetV1/Conv2d_0/"""
			lowerCamelCase_					=  backbone.conv_stem.convolution.weight
			lowerCamelCase_					=  backbone.conv_stem.normalization.bias
			lowerCamelCase_					=  backbone.conv_stem.normalization.weight
			lowerCamelCase_					=  backbone.conv_stem.normalization.running_mean
			lowerCamelCase_					=  backbone.conv_stem.normalization.running_var

			for i in range(13						):
						lowerCamelCase_					=  i + 1
						lowerCamelCase_					=  i * 2

						lowerCamelCase_					=  backbone.layer[pt_index]
						lowerCamelCase_					=  f"MobilenetV1/Conv2d_{tf_index}_depthwise/"
						lowerCamelCase_					=  pointer.convolution.weight
						lowerCamelCase_					=  pointer.normalization.bias
						lowerCamelCase_					=  pointer.normalization.weight
						lowerCamelCase_					=  pointer.normalization.running_mean
						lowerCamelCase_					=  pointer.normalization.running_var

						lowerCamelCase_					=  backbone.layer[pt_index + 1]
						lowerCamelCase_					=  f"MobilenetV1/Conv2d_{tf_index}_pointwise/"
						lowerCamelCase_					=  pointer.convolution.weight
						lowerCamelCase_					=  pointer.normalization.bias
						lowerCamelCase_					=  pointer.normalization.weight
						lowerCamelCase_					=  pointer.normalization.running_mean
						lowerCamelCase_					=  pointer.normalization.running_var

			if isinstance(lowerCAmelCase__	,lowerCAmelCase__						):
						lowerCamelCase_					=  """MobilenetV1/Logits/Conv2d_1c_1x1/"""
						lowerCamelCase_					=  model.classifier.weight
						lowerCamelCase_					=  model.classifier.bias

			return tf_to_pt_map






def  lowercase						(	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
			lowerCamelCase_					=  tf.train.list_variables(lowerCAmelCase__						)
			lowerCamelCase_					=  {}
			for name, shape in init_vars:
						logger.info(f"Loading TF weight {name} with shape {shape}"						)
						lowerCamelCase_					=  tf.train.load_variable(lowerCAmelCase__	,lowerCAmelCase__						)
						lowerCamelCase_					=  array

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

						lowerCamelCase_					=  tf_weights[name]

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

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

			if in_width % stride_width == 0:
						lowerCamelCase_					=  max(kernel_width - stride_width	,0						)
			else:
						lowerCamelCase_					=  max(kernel_width - (in_width % stride_width)	,0						)

			lowerCamelCase_					=  pad_along_width // 2
			lowerCamelCase_					=  pad_along_width - pad_left
			lowerCamelCase_					=  pad_along_height // 2
			lowerCamelCase_					=  pad_along_height - pad_top

			lowerCamelCase_					=  (pad_left, pad_right, pad_top, pad_bottom)
			return nn.functional.pad(lowerCAmelCase__	,lowerCAmelCase__	,'''constant'''	,0.0						)




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase = 1							,						UpperCAmelCase = 1							,						UpperCAmelCase = False							,						UpperCAmelCase = True							,						UpperCAmelCase = True							,						):
							super().__init__()
							lowerCamelCase_					=  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."   )

							lowerCamelCase_					=  0 if config.tf_padding else int((kernel_size - 1) / 2   )

							lowerCamelCase_					=  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:
										lowerCamelCase_					=  nn.BatchNormad(
										    num_features=__snake_case							,						eps=config.layer_norm_eps							,						momentum=0.9_9_9_7							,						affine=__snake_case							,						track_running_stats=__snake_case							,						)
							else:
										lowerCamelCase_					=  None

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





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):

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




class  __lowerCamelCase  ( UpperCamelCase__			):
				a__:      Optional[int]          =    MobileNetVaConfig
				a__:      str          =    load_tf_weights_in_mobilenet_va
				a__:      Dict          =    'mobilenet_v1'
				a__:      List[Any]          =    'pixel_values'
				a__:      Dict          =    False




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):

							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   )

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

A_    							=					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.'						,	UpperCamelCase__						,	)
class  __lowerCamelCase  ( UpperCamelCase__			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase = True   ):
							super().__init__(__snake_case   )
							lowerCamelCase_					=  config

							lowerCamelCase_					=  32
							lowerCamelCase_					=  max(int(depth * config.depth_multiplier   )							,						config.min_depth   )

							lowerCamelCase_					=  MobileNetVaConvLayer(
							    __snake_case							,						in_channels=config.num_channels							,						out_channels=__snake_case							,						kernel_size=3							,						stride=2							,						)

							lowerCamelCase_					=  [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

							lowerCamelCase_					=  nn.ModuleList()
							for i in range(13   ):
										lowerCamelCase_					=  out_channels

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

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

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




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							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							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						):
							lowerCamelCase_					=  (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							lowerCamelCase_					=  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'''   )

							lowerCamelCase_					=  self.conv_stem(__snake_case   )

							lowerCamelCase_					=  () if output_hidden_states else None

							for i, layer_module in enumerate(self.layer   ):
										lowerCamelCase_					=  layer_module(__snake_case   )

										if output_hidden_states:
													lowerCamelCase_					=  all_hidden_states + (hidden_states,)

							lowerCamelCase_					=  hidden_states

							if self.pooler is not None:
										lowerCamelCase_					=  torch.flatten(self.pooler(__snake_case   )							,						start_dim=1   )
							else:
										lowerCamelCase_					=  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  __lowerCamelCase  ( UpperCamelCase__			):




				def __init__(				self							,						UpperCAmelCase   ):
							super().__init__(__snake_case   )

							lowerCamelCase_					=  config.num_labels
							lowerCamelCase_					=  MobileNetVaModel(__snake_case   )

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

							# Classifier head
							lowerCamelCase_					=  nn.Dropout(config.classifier_dropout_prob							,						inplace=__snake_case   )
							lowerCamelCase_					=  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							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						):
							lowerCamelCase_					=  return_dict if return_dict is not None else self.config.use_return_dict

							lowerCamelCase_					=  self.mobilenet_va(__snake_case							,						output_hidden_states=__snake_case							,						return_dict=__snake_case   )

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

							lowerCamelCase_					=  self.classifier(self.dropout(__snake_case   )   )

							lowerCamelCase_					=  None
							if labels is not None:
										if self.config.problem_type is None:
													if self.num_labels == 1:
																lowerCamelCase_					=  """regression"""
													elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																lowerCamelCase_					=  """single_label_classification"""
													else:
																lowerCamelCase_					=  """multi_label_classification"""

										if self.config.problem_type == "regression":
													lowerCamelCase_					=  MSELoss()
													if self.num_labels == 1:
																lowerCamelCase_					=  loss_fct(logits.squeeze()							,						labels.squeeze()   )
													else:
																lowerCamelCase_					=  loss_fct(__snake_case							,						__snake_case   )
										elif self.config.problem_type == "single_label_classification":
													lowerCamelCase_					=  CrossEntropyLoss()
													lowerCamelCase_					=  loss_fct(logits.view(-1							,						self.num_labels   )							,						labels.view(-1   )   )
										elif self.config.problem_type == "multi_label_classification":
													lowerCamelCase_					=  BCEWithLogitsLoss()
													lowerCamelCase_					=  loss_fct(__snake_case							,						__snake_case   )

							if not return_dict:
										lowerCamelCase_					=  (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 sklearn.metrics import matthews_corrcoef

import datasets


UpperCAmelCase_		:					Dict          =  "\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

UpperCAmelCase_		:					Any          =  "\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

UpperCAmelCase_		:					Dict          =  "\\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,    _KWARGS_DESCRIPTION      )
class 		__A   (      datasets.Metric      ):

						def      A__    (		self :List[str]			):
										'''simple docstring'''

										return datasets.MetricInfo(
										    description=_DESCRIPTION     ,			citation=_CITATION     ,			inputs_description=_KWARGS_DESCRIPTION     ,			features=datasets.Features(
										        {
										            """predictions""": datasets.Value("""int32"""			),
										            """references""": datasets.Value("""int32"""			),
										        }			)     ,			reference_urls=[
										        """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html"""
										    ]     ,			)


						def      A__    (		self :Tuple     ,			__snake_case :str     ,			__snake_case :Tuple     ,			__snake_case :List[str]=None			):
										'''simple docstring'''

										return {
										    "matthews_correlation": float(matthews_corrcoef(__snake_case     ,			__snake_case     ,			sample_weight=__snake_case			)			),
										}




