




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


UpperCAmelCase_		:					List[Any]          =  logging.get_logger(__name__)


# General docstring
UpperCAmelCase_		:					Optional[int]          =  "MobileNetV1Config"

# Base docstring
UpperCAmelCase_		:					str          =  "google/mobilenet_v1_1.0_224"
UpperCAmelCase_		:					Tuple          =  [1, 1024, 7, 7]

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


UpperCAmelCase_		:					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 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase						,  lowerCamelCase=None ):
				__magic_name__						:						Optional[int]										={}

				if isinstance(lowerCamelCase						,  lowerCamelCase ):
								__magic_name__						:						Optional[Any]										=model.mobilenet_va
				else:
								__magic_name__						:						str										=model

				__magic_name__						:						Tuple										="""MobilenetV1/Conv2d_0/"""
				__magic_name__						:						str										=backbone.conv_stem.convolution.weight
				__magic_name__						:						Any										=backbone.conv_stem.normalization.bias
				__magic_name__						:						Union[str, Any]										=backbone.conv_stem.normalization.weight
				__magic_name__						:						Optional[Any]										=backbone.conv_stem.normalization.running_mean
				__magic_name__						:						Any										=backbone.conv_stem.normalization.running_var

				for i in range(13 ):
								__magic_name__						:						Optional[Any]										=i + 1
								__magic_name__						:						List[str]										=i * 2

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

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

				if isinstance(lowerCamelCase						,  lowerCamelCase ):
								__magic_name__						:						Optional[int]										="""MobilenetV1/Logits/Conv2d_1c_1x1/"""
								__magic_name__						:						str										=model.classifier.weight
								__magic_name__						:						str										=model.classifier.bias

				return tf_to_pt_map




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

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

								__magic_name__						:						Optional[Any]										=tf_weights[name]

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

				if in_height % stride_height == 0:
								__magic_name__						:						List[str]										=max(kernel_height - stride_height						,  0 )
				else:
								__magic_name__						:						int										=max(kernel_height - (in_height % stride_height)						,  0 )

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

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

				__magic_name__						:						int										=(pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(lowerCamelCase						,  lowerCamelCase						,  """constant"""						,  0.0 )




class 		__A   (      nn.Module      ):

						def __init__(		self :Tuple     ,			__snake_case :MobileNetVaConfig     ,			__snake_case :int     ,			__snake_case :int     ,			__snake_case :int     ,			__snake_case :Optional[int] = 1     ,			__snake_case :Optional[int] = 1     ,			__snake_case :bool = False     ,			__snake_case :Optional[bool] = True     ,			__snake_case :Optional[bool or str] = True     ,			):
										'''simple docstring'''

										super().__init__()
										__magic_name__						:						Union[str, 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."			)

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

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

										if use_activation:
														if isinstance(__snake_case     ,			__snake_case			):
																		__magic_name__						:						int										=ACTaFN[use_activation]
														elif isinstance(config.hidden_act     ,			__snake_case			):
																		__magic_name__						:						List[Any]										=ACTaFN[config.hidden_act]
														else:
																		__magic_name__						:						Tuple										=config.hidden_act
										else:
														__magic_name__						:						Any										=None


						def      A__    (		self :Union[str, Any]     ,			__snake_case :torch.Tensor			):
										'''simple docstring'''

										if self.config.tf_padding:
														__magic_name__						:						Tuple										=apply_tf_padding(__snake_case     ,			self.convolution			)
										__magic_name__						:						int										=self.convolution(__snake_case			)
										if self.normalization is not None:
														__magic_name__						:						Optional[Any]										=self.normalization(__snake_case			)
										if self.activation is not None:
														__magic_name__						:						Dict										=self.activation(__snake_case			)
										return features




class 		__A   (      UpperCamelCase__      ):
						UpperCamelCase      =       MobileNetVaConfig
						UpperCamelCase      =       load_tf_weights_in_mobilenet_va
						UpperCamelCase      =       """mobilenet_v1"""
						UpperCamelCase      =       """pixel_values"""
						UpperCamelCase      =       False

						def      A__    (		self :Dict     ,			__snake_case :Union[nn.Linear, nn.Convad]			):
										'''simple docstring'''

										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			)


UpperCAmelCase_		:					Optional[Any]          =  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"

UpperCAmelCase_		:					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."""       ,    UpperCamelCase__       ,    )
class 		__A   (      UpperCamelCase__      ):

						def __init__(		self :Union[str, Any]     ,			__snake_case :MobileNetVaConfig     ,			__snake_case :bool = True			):
										'''simple docstring'''

										super().__init__(__snake_case			)
										__magic_name__						:						Tuple										=config

										__magic_name__						:						int										=32
										__magic_name__						:						Optional[int]										=max(int(depth * config.depth_multiplier			)     ,			config.min_depth			)

										__magic_name__						:						str										=MobileNetVaConvLayer(
										    __snake_case     ,			in_channels=config.num_channels     ,			out_channels=__snake_case     ,			kernel_size=3     ,			stride=2     ,			)

										__magic_name__						:						List[Any]										=[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

										__magic_name__						:						List[str]										=nn.ModuleList()
										for i in range(13			):
														__magic_name__						:						Optional[int]										=out_channels

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

										__magic_name__						:						Optional[Any]										=nn.AdaptiveAvgPoolad((1, 1)			) if add_pooling_layer else None

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

						def      A__    (		self :Optional[int]     ,			__snake_case :Optional[int]			):
										'''simple docstring'''

										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      A__    (		self :Union[str, Any]     ,			__snake_case :Optional[torch.Tensor] = None     ,			__snake_case :Optional[bool] = None     ,			__snake_case :Optional[bool] = None     ,			):
										'''simple docstring'''

										__magic_name__						:						str										=(
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										__magic_name__						:						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"""			)

										__magic_name__						:						Any										=self.conv_stem(__snake_case			)

										__magic_name__						:						Optional[int]										=() if output_hidden_states else None

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

														if output_hidden_states:
																		__magic_name__						:						int										=all_hidden_states + (hidden_states,)

										__magic_name__						:						Optional[int]										=hidden_states

										if self.pooler is not None:
														__magic_name__						:						str										=torch.flatten(self.pooler(__snake_case			)     ,			start_dim=1			)
										else:
														__magic_name__						:						Tuple										=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(
    """
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """       ,    UpperCamelCase__       ,    )
class 		__A   (      UpperCamelCase__      ):

						def __init__(		self :int     ,			__snake_case :MobileNetVaConfig			):
										'''simple docstring'''

										super().__init__(__snake_case			)

										__magic_name__						:						Any										=config.num_labels
										__magic_name__						:						List[Any]										=MobileNetVaModel(__snake_case			)

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

										# Classifier head
										__magic_name__						:						List[Any]										=nn.Dropout(config.classifier_dropout_prob     ,			inplace=__snake_case			)
										__magic_name__						:						Dict										=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      A__    (		self :List[str]     ,			__snake_case :Optional[torch.Tensor] = None     ,			__snake_case :Optional[bool] = None     ,			__snake_case :Optional[torch.Tensor] = None     ,			__snake_case :Optional[bool] = None     ,			):
										'''simple docstring'''

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

										__magic_name__						:						Any										=self.mobilenet_va(__snake_case     ,			output_hidden_states=__snake_case     ,			return_dict=__snake_case			)

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

										__magic_name__						:						List[Any]										=self.classifier(self.dropout(__snake_case			)			)

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

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

										if not return_dict:
														__magic_name__						:						int										=(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     ,			)










import os
from typing import Dict, List, Union

import tensorflow as tf
from keras_nlp.tokenizers import BytePairTokenizer
from tensorflow_text import pad_model_inputs

from .tokenization_gpta import GPTaTokenizer




class 		__A   (      tf.keras.layers.Layer      ):

						def __init__(		self :Optional[int]     ,			__snake_case :Dict[str, int]     ,			__snake_case :List[str]     ,			__snake_case :int = None     ,			__snake_case :int = None			):
										'''simple docstring'''

										super().__init__()
										__magic_name__						:						Optional[int]										=pad_token_id
										__magic_name__						:						List[Any]										=max_length
										__magic_name__						:						Dict										=vocab
										__magic_name__						:						int										=merges
										__magic_name__						:						Optional[int]										=BytePairTokenizer(__snake_case     ,			__snake_case     ,			sequence_length=__snake_case			)

						@classmethod
						def      A__    (		cls :List[Any]     ,			__snake_case :GPTaTokenizer     ,			*__snake_case :int     ,			**__snake_case :Any			):
										'''simple docstring'''

										__magic_name__						:						List[Any]										=[""" """.join(__snake_case			) for m in tokenizer.bpe_ranks.keys()]
										__magic_name__						:						str										=tokenizer.get_vocab()
										return cls(__snake_case     ,			__snake_case     ,			*__snake_case     ,			**__snake_case			)

						@classmethod
						def      A__    (		cls :Dict     ,			__snake_case :Union[str, os.PathLike]     ,			*__snake_case :Union[str, Any]     ,			**__snake_case :int			):
										'''simple docstring'''

										__magic_name__						:						Dict										=GPTaTokenizer.from_pretrained(__snake_case     ,			*__snake_case     ,			**__snake_case			)
										return cls.from_tokenizer(__snake_case     ,			*__snake_case     ,			**__snake_case			)

						@classmethod
						def      A__    (		cls :Optional[Any]     ,			__snake_case :List[Any]			):
										'''simple docstring'''

										return cls(**__snake_case			)

						def      A__    (		self :Union[str, Any]			):
										'''simple docstring'''

										return {
										    "vocab": self.vocab,
										    "merges": self.merges,
										    "max_length": self.max_length,
										    "pad_token_id": self.pad_token_id,
										}


						def      A__    (		self :List[Any]     ,			__snake_case :Dict     ,			__snake_case :int = None			):
										'''simple docstring'''

										__magic_name__						:						Optional[Any]										=self.tf_tokenizer(__snake_case			)
										__magic_name__						:						Tuple										=tf.ones_like(__snake_case			)

										if self.pad_token_id is not None:
														# pad the tokens up to max length
														__magic_name__						:						Tuple										=max_length if max_length is not None else self.max_length

														if max_length is not None:
																		__magic_name__					,			__magic_name__						:						Tuple										=pad_model_inputs(
																		    __snake_case     ,			max_seq_length=__snake_case     ,			pad_value=self.pad_token_id			)

										return {"attention_mask": attention_mask, "input_ids": input_ids}




