





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		:  Union[str, Any]			       =logging.get_logger(__name__)


# General docstring
_lowercase		:  List[str]			       ="MobileNetV1Config"

# Base docstring
_lowercase		:  int			       ="google/mobilenet_v1_1.0_224"
_lowercase		:  List[Any]			       =[1, 1024, 7, 7]

# Image classification docstring
_lowercase		:  Optional[int]			       ="google/mobilenet_v1_1.0_224"
_lowercase		:  List[Any]			       ="tabby, tabby cat"


_lowercase		:  Union[str, Any]			       =[
    "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 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__=None						):
		lowerCamelCase_	:     str 						=      {}

		if isinstance(__lowercase							,__lowercase						):
				lowerCamelCase_	:     Any 						=      model.mobilenet_va
		else:
				lowerCamelCase_	:     str 						=      model

		lowerCamelCase_	:     Any 						=      'MobilenetV1/Conv2d_0/'
		lowerCamelCase_	:     Any 						=      backbone.conv_stem.convolution.weight
		lowerCamelCase_	:     int 						=      backbone.conv_stem.normalization.bias
		lowerCamelCase_	:     Optional[int] 						=      backbone.conv_stem.normalization.weight
		lowerCamelCase_	:     Dict 						=      backbone.conv_stem.normalization.running_mean
		lowerCamelCase_	:     Any 						=      backbone.conv_stem.normalization.running_var

		for i in range(13						):
				lowerCamelCase_	:     Dict 						=      i + 1
				lowerCamelCase_	:     Optional[Any] 						=      i * 2

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

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

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

		return tf_to_pt_map


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

		# Build TF to PyTorch weights loading map
		lowerCamelCase_	:     int 						=      _build_tf_to_pytorch_map(__lowercase							,__lowercase							,__lowercase						)

		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_	:     str 						=      tf_weights[name]

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

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

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


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__						):
		lowerCamelCase_						,      lowerCamelCase_	:     Union[str, Any] 						=      features.shape[-2:]
		lowerCamelCase_						,      lowerCamelCase_	:     int 						=      conv_layer.stride
		lowerCamelCase_						,      lowerCamelCase_	:     List[Any] 						=      conv_layer.kernel_size

		if in_height % stride_height == 0:
				lowerCamelCase_	:     Union[str, Any] 						=      max(kernel_height - stride_height							,0						)
		else:
				lowerCamelCase_	:     Optional[Any] 						=      max(kernel_height - (in_height % stride_height)							,0						)

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

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

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






class 						UpperCamelCase_  (  nn.Module							):



					def __init__(		self     :     int       ,      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       ,      ):
							super().__init__()
							lowerCamelCase_	:     Dict 						=      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_	:     Dict 						=      0 if config.tf_padding else int((kernel_size - 1) / 2						)

							lowerCamelCase_	:     Optional[Any] 						=      nn.Convad(
							    in_channels=UpperCamelCase_       ,      out_channels=UpperCamelCase_       ,      kernel_size=UpperCamelCase_       ,      stride=UpperCamelCase_       ,      padding=UpperCamelCase_       ,      groups=UpperCamelCase_       ,      bias=UpperCamelCase_       ,      padding_mode='zeros'       ,      )

							if use_normalization:
									lowerCamelCase_	:     Any 						=      nn.BatchNormad(
									    num_features=UpperCamelCase_       ,      eps=config.layer_norm_eps       ,      momentum=0.9_997       ,      affine=UpperCamelCase_       ,      track_running_stats=UpperCamelCase_       ,      )
							else:
									lowerCamelCase_	:     Optional[Any] 						=      None

							if use_activation:
									if isinstance(UpperCamelCase_       ,      UpperCamelCase_						):
											lowerCamelCase_	:     List[str] 						=      ACTaFN[use_activation]
									elif isinstance(config.hidden_act       ,      UpperCamelCase_						):
											lowerCamelCase_	:     int 						=      ACTaFN[config.hidden_act]
									else:
											lowerCamelCase_	:     Tuple 						=      config.hidden_act
							else:
									lowerCamelCase_	:     Dict 						=      None





					def   __a     (		self     :     Union[str, Any]       ,      lowerCamelCase     :     torch.Tensor						):



							if self.config.tf_padding:
									lowerCamelCase_	:     str 						=      apply_tf_padding(UpperCamelCase_       ,      self.convolution						)
							lowerCamelCase_	:     Any 						=      self.convolution(UpperCamelCase_						)
							if self.normalization is not None:
									lowerCamelCase_	:     Union[str, Any] 						=      self.normalization(UpperCamelCase_						)
							if self.activation is not None:
									lowerCamelCase_	:     Union[str, Any] 						=      self.activation(UpperCamelCase_						)
							return features






class 						UpperCamelCase_  (  lowercase_							):
					_a      :						Tuple						    =					MobileNetVaConfig
					_a      :						Optional[Any]						    =					load_tf_weights_in_mobilenet_va
					_a      :						List[Any]						    =					'mobilenet_v1'
					_a      :						int						    =					'pixel_values'
					_a      :						Dict						    =					False



					def   __a     (		self     :     Optional[Any]       ,      lowerCamelCase     :     Union[nn.Linear, nn.Convad]						):



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

_lowercase		:  int			       =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.'  ,     lowercase_  ,     )
class 						UpperCamelCase_  (  lowercase_							):



					def __init__(		self     :     int       ,      lowerCamelCase     :     MobileNetVaConfig       ,      lowerCamelCase     :     bool = True						):
							super().__init__(UpperCamelCase_						)
							lowerCamelCase_	:     Optional[Any] 						=      config

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

							lowerCamelCase_	:     Tuple 						=      MobileNetVaConvLayer(
							    UpperCamelCase_       ,      in_channels=config.num_channels       ,      out_channels=UpperCamelCase_       ,      kernel_size=3       ,      stride=2       ,      )

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

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

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

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

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

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

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



					def   __a     (		self     :     Optional[int]       ,      lowerCamelCase     :     Optional[int]						):
							raise NotImplementedError





					@add_start_docstrings_to_model_forward(UpperCamelCase_						)
					@add_code_sample_docstrings(
					    checkpoint=_CHECKPOINT_FOR_DOC       ,      output_type=UpperCamelCase_       ,      config_class=_CONFIG_FOR_DOC       ,      modality='vision'       ,      expected_output=_EXPECTED_OUTPUT_SHAPE       ,      )
					def   __a     (		self     :     Any       ,      lowerCamelCase     :     Optional[torch.Tensor] = None       ,      lowerCamelCase     :     Optional[bool] = None       ,      lowerCamelCase     :     Optional[bool] = None       ,      ):
							lowerCamelCase_	:     Optional[Any] 						=      (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							lowerCamelCase_	:     List[Any] 						=      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_	:     int 						=      self.conv_stem(UpperCamelCase_						)

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

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

									if output_hidden_states:
											lowerCamelCase_	:     Optional[int] 						=      all_hidden_states + (hidden_states,)

							lowerCamelCase_	:     Optional[Any] 						=      hidden_states

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






@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    '  ,     lowercase_  ,     )
class 						UpperCamelCase_  (  lowercase_							):



					def __init__(		self     :     Optional[int]       ,      lowerCamelCase     :     MobileNetVaConfig						):
							super().__init__(UpperCamelCase_						)

							lowerCamelCase_	:     str 						=      config.num_labels
							lowerCamelCase_	:     str 						=      MobileNetVaModel(UpperCamelCase_						)

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

							# Classifier head
							lowerCamelCase_	:     Union[str, Any] 						=      nn.Dropout(config.classifier_dropout_prob       ,      inplace=UpperCamelCase_						)
							lowerCamelCase_	:     List[str] 						=      nn.Linear(UpperCamelCase_       ,      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(UpperCamelCase_						)
					@add_code_sample_docstrings(
					    checkpoint=_IMAGE_CLASS_CHECKPOINT       ,      output_type=UpperCamelCase_       ,      config_class=_CONFIG_FOR_DOC       ,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT       ,      )
					def   __a     (		self     :     Tuple       ,      lowerCamelCase     :     Optional[torch.Tensor] = None       ,      lowerCamelCase     :     Optional[bool] = None       ,      lowerCamelCase     :     Optional[torch.Tensor] = None       ,      lowerCamelCase     :     Optional[bool] = None       ,      ):
							lowerCamelCase_	:     List[Any] 						=      return_dict if return_dict is not None else self.config.use_return_dict

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

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

							lowerCamelCase_	:     Any 						=      self.classifier(self.dropout(UpperCamelCase_						)						)

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

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

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

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








from __future__ import annotations

from typing import Generic, TypeVar

__a   :							str						= TypeVar("T")


class    __lowercase   (						Generic[T]	):







     '''simple docstring'''




     def __init__(					self							:      Any			,						UpperCamelCase_							:      T					):


         """simple docstring"""



         __A       =						data
         __A       =						self
         __A       =						0


class    __lowercase   (						Generic[T]	):







     '''simple docstring'''




     def __init__(					self							:      Optional[Any]					):


         """simple docstring"""



         __A       =						{}




     def 		lowerCAmelCase_  (					self							:      Union[str, Any]			,						UpperCamelCase_							:      T					):


         """simple docstring"""



         __A       =						DisjointSetTreeNode(UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      List[Any]			,						UpperCamelCase_							:      T					):


         """simple docstring"""



         __A       =						self.map[data]
         if elem_ref != elem_ref.parent:
             __A       =						self.find_set(elem_ref.parent.data					)
         return elem_ref.parent




     def 		lowerCAmelCase_  (					self							:      int			,						UpperCamelCase_							:      DisjointSetTreeNode[T]			,						UpperCamelCase_							:      DisjointSetTreeNode[T]					):


         """simple docstring"""



         if nodea.rank > nodea.rank:
             __A       =						nodea
         else:
             __A       =						nodea
             if nodea.rank == nodea.rank:
                 nodea.rank += 1





     def 		lowerCAmelCase_  (					self							:      Tuple			,						UpperCamelCase_							:      T			,						UpperCamelCase_							:      T					):


         """simple docstring"""



         self.link(self.find_set(UpperCamelCase_					)			,						self.find_set(UpperCamelCase_					)					)


class    __lowercase   (						Generic[T]	):







     '''simple docstring'''




     def __init__(					self							:      Optional[int]					):


         """simple docstring"""



         __A       =						{}




     def 		lowerCAmelCase_  (					self							:      int			,						UpperCamelCase_							:      T					):


         """simple docstring"""



         if node not in self.connections:
             __A       =						{}




     def 		lowerCAmelCase_  (					self							:      Dict			,						UpperCamelCase_							:      T			,						UpperCamelCase_							:      T			,						UpperCamelCase_							:      int					):


         """simple docstring"""



         self.add_node(UpperCamelCase_					)
         self.add_node(UpperCamelCase_					)
         __A       =						weight
         __A       =						weight





     def 		lowerCAmelCase_  (					self							:      Dict					):


         """simple docstring"""



         __A       =						[]
         __A       =						set()
         for start in self.connections:
             for end in self.connections[start]:
                 if (start, end) not in seen:
                     seen.add((end, start)					)
                     edges.append((start, end, self.connections[start][end])					)
         edges.sort(key=lambda UpperCamelCase_					: x[2]					)

         # creating the disjoint set
         __A       =						DisjointSetTree[T]()
         for node in self.connections:
             disjoint_set.make_set(UpperCamelCase_					)

         # MST generation
         __A       =						0
         __A       =						0
         __A       =						GraphUndirectedWeighted[T]()
         while num_edges < len(self.connections					) - 1:
             __A     ,						__A     ,						__A       =						edges[index]
             index += 1
             __A       =						disjoint_set.find_set(UpperCamelCase_					)
             __A       =						disjoint_set.find_set(UpperCamelCase_					)
             if parent_u != parent_v:
                 num_edges += 1
                 graph.add_edge(UpperCamelCase_			,						UpperCamelCase_			,						UpperCamelCase_					)
                 disjoint_set.union(UpperCamelCase_			,						UpperCamelCase_					)
         return graph




