

"""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__					:	Dict				    =	logging.get_logger(__name__)


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

# Base docstring
lowerCamelCase__					:	Dict				    =	'''google/mobilenet_v1_1.0_224'''
lowerCamelCase__					:	Dict				    =	[1, 10_24, 7, 7]

# Image classification docstring
lowerCamelCase__					:	Tuple				    =	'''google/mobilenet_v1_1.0_224'''
lowerCamelCase__					:	List[str]				    =	'''tabby, tabby cat'''


lowerCamelCase__					:	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    UpperCamelCase       (      _lowerCAmelCase  :    Optional[int],	_lowerCAmelCase  :    List[str],	_lowerCAmelCase  :    Optional[int]=None			)					->      Tuple:
	_UpperCAmelCase     :				Union[str, Any]          =       {}

	if isinstance(A_,	A_			):
		_UpperCAmelCase     :				List[Any]          =       model.mobilenet_va
	else:
		_UpperCAmelCase     :				Optional[Any]          =       model

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

	for i in range(13			):
		_UpperCAmelCase     :				str          =       i + 1
		_UpperCAmelCase     :				Any          =       i * 2

		_UpperCAmelCase     :				Dict          =       backbone.layer[pt_index]
		_UpperCAmelCase     :				int          =       f'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
		_UpperCAmelCase     :				Optional[int]          =       pointer.convolution.weight
		_UpperCAmelCase     :				Dict          =       pointer.normalization.bias
		_UpperCAmelCase     :				Tuple          =       pointer.normalization.weight
		_UpperCAmelCase     :				Optional[int]          =       pointer.normalization.running_mean
		_UpperCAmelCase     :				Optional[int]          =       pointer.normalization.running_var

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

	if isinstance(A_,	A_			):
		_UpperCAmelCase     :				Dict          =       '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
		_UpperCAmelCase     :				str          =       model.classifier.weight
		_UpperCAmelCase     :				Union[str, Any]          =       model.classifier.bias

	return tf_to_pt_map
def    UpperCamelCase       (      _lowerCAmelCase  :    Optional[Any],	_lowerCAmelCase  :    List[Any],	_lowerCAmelCase  :    List[str]			)					->      Union[str, Any]:
	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
	_UpperCAmelCase     :				Optional[Any]          =       tf.train.list_variables(A_			)
	_UpperCAmelCase     :				List[Any]          =       {}
	for name, shape in init_vars:
		logger.info(f'''Loading TF weight {name} with shape {shape}'''			)
		_UpperCAmelCase     :				Tuple          =       tf.train.load_variable(A_,	A_			)
		_UpperCAmelCase     :				Optional[int]          =       array

	# Build TF to PyTorch weights loading map
	_UpperCAmelCase     :				Optional[int]          =       _build_tf_to_pytorch_map(A_,	A_,	A_			)

	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

		_UpperCAmelCase     :				Optional[Any]          =       tf_weights[name]

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

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

	logger.info(f'''Weights not copied to PyTorch model: {", ".join(tf_weights.keys()			)}'''			)
	return model
def    UpperCamelCase       (      _lowerCAmelCase  :    Union[str, Any],	_lowerCAmelCase  :    List[str]			)					->      Optional[int]:
	_UpperCAmelCase     :				Any          =       features.shape[-2:]
	_UpperCAmelCase     :				Any          =       conv_layer.stride
	_UpperCAmelCase     :				str          =       conv_layer.kernel_size

	if in_height % stride_height == 0:
		_UpperCAmelCase     :				Dict          =       max(kernel_height - stride_height,	0			)
	else:
		_UpperCAmelCase     :				List[Any]          =       max(kernel_height - (in_height % stride_height),	0			)

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

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

	_UpperCAmelCase     :				Any          =       (pad_left, pad_right, pad_top, pad_bottom)
	return nn.functional.pad(A_,	A_,	"""constant""",	0.0			)






class      _UpperCAmelCase      (		nn.Module):
			def __init__(		self   ,		_A   ,		_A   ,		_A   ,		_A   ,		_A = 1   ,		_A = 1   ,		_A = False   ,		_A = True   ,		_A = True   ,		)     ->     List[Any]:






				'''simple docstring'''







				super().__init__()
				_UpperCAmelCase     :				Optional[Any]          =       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.'''  )

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

				_UpperCAmelCase     :				str          =       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:
					_UpperCAmelCase     :				Optional[Any]          =       nn.BatchNormad(
					    num_features=lowercase_   ,		eps=config.layer_norm_eps   ,		momentum=0.9997   ,		affine=lowercase_   ,		track_running_stats=lowercase_   ,		)
				else:
					_UpperCAmelCase     :				int          =       None

				if use_activation:
					if isinstance(lowercase_   ,		lowercase_  ):
						_UpperCAmelCase     :				Dict          =       ACTaFN[use_activation]
					elif isinstance(config.hidden_act   ,		lowercase_  ):
						_UpperCAmelCase     :				Tuple          =       ACTaFN[config.hidden_act]
					else:
						_UpperCAmelCase     :				Dict          =       config.hidden_act
				else:
					_UpperCAmelCase     :				List[Any]          =       None
			def 				__snake_case			(		self   ,		_A  )     ->     Dict:






				'''simple docstring'''







				if self.config.tf_padding:
					_UpperCAmelCase     :				Optional[Any]          =       apply_tf_padding(lowercase_   ,		self.convolution  )
				_UpperCAmelCase     :				Optional[Any]          =       self.convolution(lowercase_  )
				if self.normalization is not None:
					_UpperCAmelCase     :				Optional[Any]          =       self.normalization(lowercase_  )
				if self.activation is not None:
					_UpperCAmelCase     :				Any          =       self.activation(lowercase_  )
				return features






class      _UpperCAmelCase      (		a_):
			__a			:							Optional[Any]					       =				MobileNetVaConfig
			__a			:							str					       =				load_tf_weights_in_mobilenet_va
			__a			:							str					       =				"""mobilenet_v1"""
			__a			:							Dict					       =				"""pixel_values"""
			__a			:							Optional[Any]					       =				False
			def 				__snake_case			(		self   ,		_A  )     ->     List[Any]:






				'''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__					:	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__					:	List[str]				    =	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      _UpperCAmelCase      (		a_):
			def __init__(		self   ,		_A   ,		_A = True  )     ->     Dict:






				'''simple docstring'''







				super().__init__(lowercase_  )
				_UpperCAmelCase     :				Union[str, Any]          =       config

				_UpperCAmelCase     :				int          =       32
				_UpperCAmelCase     :				List[Any]          =       max(int(depth * config.depth_multiplier  )   ,		config.min_depth  )

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

				_UpperCAmelCase     :				List[str]          =       [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

				_UpperCAmelCase     :				str          =       nn.ModuleList()
				for i in range(13  ):
					_UpperCAmelCase     :				Dict          =       out_channels

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

				_UpperCAmelCase     :				Any          =       nn.AdaptiveAvgPoolad((1, 1)  ) if add_pooling_layer else None

				# Initialize weights and apply final processing
				self.post_init()
			def 				__snake_case			(		self   ,		_A  )     ->     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 				__snake_case			(		self   ,		_A = None   ,		_A = None   ,		_A = None   ,		)     ->     Optional[int]:






				'''simple docstring'''







				_UpperCAmelCase     :				Dict          =       (
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)
				_UpperCAmelCase     :				Optional[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"""  )

				_UpperCAmelCase     :				Dict          =       self.conv_stem(lowercase_  )

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

				for i, layer_module in enumerate(self.layer  ):
					_UpperCAmelCase     :				Union[str, Any]          =       layer_module(lowercase_  )

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

				_UpperCAmelCase     :				Any          =       hidden_states

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






@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      _UpperCAmelCase      (		a_):
			def __init__(		self   ,		_A  )     ->     List[Any]:






				'''simple docstring'''







				super().__init__(lowercase_  )

				_UpperCAmelCase     :				Dict          =       config.num_labels
				_UpperCAmelCase     :				Optional[int]          =       MobileNetVaModel(lowercase_  )

				_UpperCAmelCase     :				Union[str, Any]          =       self.mobilenet_va.layer[-1].convolution.out_channels

				# Classifier head
				_UpperCAmelCase     :				Optional[Any]          =       nn.Dropout(config.classifier_dropout_prob   ,		inplace=lowercase_  )
				_UpperCAmelCase     :				int          =       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 				__snake_case			(		self   ,		_A = None   ,		_A = None   ,		_A = None   ,		_A = None   ,		)     ->     List[str]:






				'''simple docstring'''







				_UpperCAmelCase     :				List[Any]          =       return_dict if return_dict is not None else self.config.use_return_dict

				_UpperCAmelCase     :				Optional[Any]          =       self.mobilenet_va(lowercase_   ,		output_hidden_states=lowercase_   ,		return_dict=lowercase_  )

				_UpperCAmelCase     :				Dict          =       outputs.pooler_output if return_dict else outputs[1]

				_UpperCAmelCase     :				int          =       self.classifier(self.dropout(lowercase_  )  )

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

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

				if not return_dict:
					_UpperCAmelCase     :				Tuple          =       (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"""





import warnings

from ...utils import logging
from .image_processing_imagegpt import ImageGPTImageProcessor


__UpperCamelCase    : List[str]				 =						logging.get_logger(__name__)







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					def __init__(			self     :							Any  ,*lowercase_     :							Dict  ,**lowercase_     :							List[str]						):
						warnings.warn(
						    '''The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
						    ''' Please use ImageGPTImageProcessor instead.'''  ,lowercase_  ,)
						super().__init__(*lowercase_  ,**lowercase_						)




