




"""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, 1_0_2_4, 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    (snake_case__      :       Union[str, Any]					,				snake_case__      :       Union[str, Any]					,				snake_case__      :       List[Any]=None       )   ->     Optional[int]:


				'''simple docstring'''






				lowerCAmelCase              = {}

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

				return tf_to_pt_map





def 							lowercase    (snake_case__      :       Dict					,				snake_case__      :       List[str]					,				snake_case__      :       List[Any]       )   ->     List[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
				lowerCAmelCase              = tf.train.list_variables(snake_case__       )
				lowerCAmelCase              = {}
				for name, shape in init_vars:
								logger.info(f'''Loading TF weight {name} with shape {shape}'''       )
								lowerCAmelCase              = tf.train.load_variable(snake_case__					,				snake_case__       )
								lowerCAmelCase              = array

				# Build TF to PyTorch weights loading map
				lowerCAmelCase              = _build_tf_to_pytorch_map(snake_case__					,				snake_case__					,				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

								lowerCAmelCase              = tf_weights[name]

								if "depthwise_weights" in name:
												logger.info("""Transposing depthwise"""       )
												lowerCAmelCase              = np.transpose(snake_case__					,				(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(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}'''       )
								lowerCAmelCase              = torch.from_numpy(snake_case__       )

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

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





def 							lowercase    (snake_case__      :       torch.Tensor					,				snake_case__      :       nn.Convad       )   ->     List[Any]:


				'''simple docstring'''






				lowerCAmelCase       ,  lowerCAmelCase              = features.shape[-2:]
				lowerCAmelCase       ,  lowerCAmelCase              = conv_layer.stride
				lowerCAmelCase       ,  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(snake_case__					,				snake_case__					,				"""constant"""					,				0.0       )






class 					SCREAMING_SNAKE_CASE__    (    nn.Module    ):


						def __init__(							self :	Tuple  ,  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              = 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=SCREAMING_SNAKE_CASE_  ,  out_channels=SCREAMING_SNAKE_CASE_  ,  kernel_size=SCREAMING_SNAKE_CASE_  ,  stride=SCREAMING_SNAKE_CASE_  ,  padding=SCREAMING_SNAKE_CASE_  ,  groups=SCREAMING_SNAKE_CASE_  ,  bias=SCREAMING_SNAKE_CASE_  ,  padding_mode="""zeros"""  ,  )

										if use_normalization:
														lowerCAmelCase              = nn.BatchNormad(
														    num_features=SCREAMING_SNAKE_CASE_  ,  eps=config.layer_norm_eps  ,  momentum=0.9997  ,  affine=SCREAMING_SNAKE_CASE_  ,  track_running_stats=SCREAMING_SNAKE_CASE_  ,  )
										else:
														lowerCAmelCase              = None

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




						def      __lowercase       (							self :	List[Any]  ,  lowerCAmelCase :	torch.Tensor    ):
										if self.config.tf_padding:
														lowerCAmelCase              = apply_tf_padding(SCREAMING_SNAKE_CASE_  ,  self.convolution    )
										lowerCAmelCase              = self.convolution(SCREAMING_SNAKE_CASE_    )
										if self.normalization is not None:
														lowerCAmelCase              = self.normalization(SCREAMING_SNAKE_CASE_    )
										if self.activation is not None:
														lowerCAmelCase              = self.activation(SCREAMING_SNAKE_CASE_    )
										return features






class 					SCREAMING_SNAKE_CASE__    (    _a    ):
						_a			  =  MobileNetVaConfig
						_a			  =  load_tf_weights_in_mobilenet_va
						_a			  =  'mobilenet_v1'
						_a			  =  'pixel_values'
						_a			  =  False


						def      __lowercase       (							self :	Union[str, Any]  ,  lowerCAmelCase :	Union[nn.Linear, nn.Convad]    ):
										if isinstance(SCREAMING_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(SCREAMING_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.'  , _a  , )
class 					SCREAMING_SNAKE_CASE__    (    _a    ):


						def __init__(							self :	Optional[Any]  ,  lowerCAmelCase :	MobileNetVaConfig  ,  lowerCAmelCase :	bool = True    ):
										super().__init__(SCREAMING_SNAKE_CASE_    )
										lowerCAmelCase              = config

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

										lowerCAmelCase              = MobileNetVaConvLayer(
										    SCREAMING_SNAKE_CASE_  ,  in_channels=config.num_channels  ,  out_channels=SCREAMING_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(
														        SCREAMING_SNAKE_CASE_  ,  in_channels=SCREAMING_SNAKE_CASE_  ,  out_channels=SCREAMING_SNAKE_CASE_  ,  kernel_size=3  ,  stride=strides[i]  ,  groups=SCREAMING_SNAKE_CASE_  ,  )    )

														self.layer.append(
														    MobileNetVaConvLayer(
														        SCREAMING_SNAKE_CASE_  ,  in_channels=SCREAMING_SNAKE_CASE_  ,  out_channels=SCREAMING_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      __lowercase       (							self :	List[Any]  ,  lowerCAmelCase :	Dict    ):
										raise NotImplementedError




						@add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_    )
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC  ,  output_type=SCREAMING_SNAKE_CASE_  ,  config_class=_CONFIG_FOR_DOC  ,  modality="""vision"""  ,  expected_output=_EXPECTED_OUTPUT_SHAPE  ,  )
						def      __lowercase       (							self :	List[Any]  ,  lowerCAmelCase :	Optional[torch.Tensor] = None  ,  lowerCAmelCase :	Optional[bool] = None  ,  lowerCAmelCase :	Optional[bool] = 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(SCREAMING_SNAKE_CASE_    )

										lowerCAmelCase              = () if output_hidden_states else None

										for i, layer_module in enumerate(self.layer    ):
														lowerCAmelCase              = layer_module(SCREAMING_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(SCREAMING_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=SCREAMING_SNAKE_CASE_  ,  pooler_output=SCREAMING_SNAKE_CASE_  ,  hidden_states=SCREAMING_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    '  , _a  , )
class 					SCREAMING_SNAKE_CASE__    (    _a    ):


						def __init__(							self :	int  ,  lowerCAmelCase :	MobileNetVaConfig    ):
										super().__init__(SCREAMING_SNAKE_CASE_    )

										lowerCAmelCase              = config.num_labels
										lowerCAmelCase              = MobileNetVaModel(SCREAMING_SNAKE_CASE_    )

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

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

										lowerCAmelCase              = self.mobilenet_va(SCREAMING_SNAKE_CASE_  ,  output_hidden_states=SCREAMING_SNAKE_CASE_  ,  return_dict=SCREAMING_SNAKE_CASE_    )

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

										lowerCAmelCase              = self.classifier(self.dropout(SCREAMING_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(SCREAMING_SNAKE_CASE_  ,  SCREAMING_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(SCREAMING_SNAKE_CASE_  ,  SCREAMING_SNAKE_CASE_    )

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

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







def 				a						(							snake_case__:					list						,   snake_case__:					list						,   snake_case__:					int						,   snake_case__:					int						,   snake_case__:					int					):


				'''simple docstring'''
				if index == number_of_items:
								return 0
				lowercase_       =					0
				lowercase_       =					0
				lowercase_       =					knapsack(snake_case__						,   snake_case__						,   snake_case__						,   snake_case__						,   index + 1					)
				if weights[index] <= max_weight:
								lowercase_       =					values[index] + knapsack(
								    snake_case__						,   snake_case__						,   snake_case__						,   max_weight - weights[index]						,   index + 1					)
				return max(snake_case__						,   snake_case__					)


if __name__ == "__main__":
						import doctest

						doctest.testmod()




