






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


UpperCamelCase    :      Dict  			=		logging.get_logger(__name__)


# General docstring
UpperCamelCase    :      Dict  			=		'MobileNetV1Config'

# Base docstring
UpperCamelCase    :      Tuple  			=		'google/mobilenet_v1_1.0_224'
UpperCamelCase    :      Any  			=		[1, 10_24, 7, 7]

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


UpperCamelCase    :      Optional[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 						A__			(				__lowerCAmelCase		:			int   ,    __lowerCAmelCase		:			int   ,    __lowerCAmelCase		:			str=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 						A__			(				__lowerCAmelCase		:			Dict   ,    __lowerCAmelCase		:			Union[str, Any]   ,    __lowerCAmelCase		:			Dict						):
						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 						A__			(				__lowerCAmelCase		:			torch.Tensor   ,    __lowerCAmelCase		:			nn.Convad						):
						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(__lowerCAmelCase   ,    __lowerCAmelCase   ,    """constant"""   ,    0.0						)




class 		UpperCamelCase__    (nn.Module			):




		'''simple docstring'''





		def __init__(      self   ,_lowerCAmelCase   ,_lowerCAmelCase   ,_lowerCAmelCase   ,_lowerCAmelCase   ,_lowerCAmelCase = 1   ,_lowerCAmelCase = 1   ,_lowerCAmelCase = False   ,_lowerCAmelCase = True   ,_lowerCAmelCase = 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=_lowerCAmelCase   ,out_channels=_lowerCAmelCase   ,kernel_size=_lowerCAmelCase   ,stride=_lowerCAmelCase   ,padding=_lowerCAmelCase   ,groups=_lowerCAmelCase   ,bias=_lowerCAmelCase   ,padding_mode="""zeros"""   ,)

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

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






		def 			UpperCamelCase_					(      self   ,_lowerCAmelCase       ):
								if self.config.tf_padding:
														lowerCamelCase__         =  apply_tf_padding(_lowerCAmelCase   ,self.convolution       )
								lowerCamelCase__         =  self.convolution(_lowerCAmelCase       )
								if self.normalization is not None:
														lowerCamelCase__         =  self.normalization(_lowerCAmelCase       )
								if self.activation is not None:
														lowerCamelCase__         =  self.activation(_lowerCAmelCase       )
								return features




class 		UpperCamelCase__    (a			):




		'''simple docstring'''





		_UpperCamelCase				  =					MobileNetVaConfig
		_UpperCamelCase				  =					load_tf_weights_in_mobilenet_va
		_UpperCamelCase				  =					'mobilenet_v1'
		_UpperCamelCase				  =					'pixel_values'
		_UpperCamelCase				  =					False






		def 			UpperCamelCase_					(      self   ,_lowerCAmelCase       ):
								if isinstance(_lowerCAmelCase   ,(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(_lowerCAmelCase   ,nn.BatchNormad       ):
														module.bias.data.zero_()
														module.weight.data.fill_(1.0       )



UpperCamelCase    :      int  			=		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    :      List[str]  			=		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 		UpperCamelCase__    (a			):




		'''simple docstring'''





		def __init__(      self   ,_lowerCAmelCase   ,_lowerCAmelCase = True       ):
								super().__init__(_lowerCAmelCase       )
								lowerCamelCase__         =  config

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

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

														self.layer.append(
														    MobileNetVaConvLayer(
														        _lowerCAmelCase   ,in_channels=_lowerCAmelCase   ,out_channels=_lowerCAmelCase   ,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   ,_lowerCAmelCase       ):
								raise NotImplementedError






		@add_start_docstrings_to_model_forward(_lowerCAmelCase       )
		@add_code_sample_docstrings(
		    checkpoint=_CHECKPOINT_FOR_DOC   ,output_type=_lowerCAmelCase   ,config_class=_CONFIG_FOR_DOC   ,modality="""vision"""   ,expected_output=_EXPECTED_OUTPUT_SHAPE   ,)
		def 			UpperCamelCase_					(      self   ,_lowerCAmelCase = None   ,_lowerCAmelCase = None   ,_lowerCAmelCase = 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(_lowerCAmelCase       )

								lowerCamelCase__         =  () if output_hidden_states else None

								for i, layer_module in enumerate(self.layer       ):
														lowerCamelCase__         =  layer_module(_lowerCAmelCase       )

														if output_hidden_states:
																				lowerCamelCase__         =  all_hidden_states + (hidden_states,)

								lowerCamelCase__         =  hidden_states

								if self.pooler is not None:
														lowerCamelCase__         =  torch.flatten(self.pooler(_lowerCAmelCase       )   ,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=_lowerCAmelCase   ,pooler_output=_lowerCAmelCase   ,hidden_states=_lowerCAmelCase   ,)




@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			):




		'''simple docstring'''





		def __init__(      self   ,_lowerCAmelCase       ):
								super().__init__(_lowerCAmelCase       )

								lowerCamelCase__         =  config.num_labels
								lowerCamelCase__         =  MobileNetVaModel(_lowerCAmelCase       )

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

								# Classifier head
								lowerCamelCase__         =  nn.Dropout(config.classifier_dropout_prob   ,inplace=_lowerCAmelCase       )
								lowerCamelCase__         =  nn.Linear(_lowerCAmelCase   ,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(_lowerCAmelCase       )
		@add_code_sample_docstrings(
		    checkpoint=_IMAGE_CLASS_CHECKPOINT   ,output_type=_lowerCAmelCase   ,config_class=_CONFIG_FOR_DOC   ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT   ,)
		def 			UpperCamelCase_					(      self   ,_lowerCAmelCase = None   ,_lowerCAmelCase = None   ,_lowerCAmelCase = None   ,_lowerCAmelCase = None   ,):
								lowerCamelCase__         =  return_dict if return_dict is not None else self.config.use_return_dict

								lowerCamelCase__         =  self.mobilenet_va(_lowerCAmelCase   ,output_hidden_states=_lowerCAmelCase   ,return_dict=_lowerCAmelCase       )

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

								lowerCamelCase__         =  self.classifier(self.dropout(_lowerCAmelCase       )       )

								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(_lowerCAmelCase   ,_lowerCAmelCase       )
														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(_lowerCAmelCase   ,_lowerCAmelCase       )

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

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









'''simple docstring'''







import argparse

import torch
from torch import nn

from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration
def 						A__			(				__lowerCAmelCase		:			Union[str, Any]						):
						lowerCamelCase__         =  [
						    """encoder.version""",
						    """decoder.version""",
						    """model.encoder.version""",
						    """model.decoder.version""",
						    """decoder.output_projection.weight""",
						    """_float_tensor""",
						    """encoder.embed_positions._float_tensor""",
						    """decoder.embed_positions._float_tensor""",
						]
						for k in ignore_keys:
												state_dict.pop(__lowerCAmelCase   ,    __lowerCAmelCase						)
def 						A__			(				__lowerCAmelCase		:			Tuple						):
						lowerCamelCase__       ,			lowerCamelCase__         =  emb.weight.shape
						lowerCamelCase__         =  nn.Linear(__lowerCAmelCase   ,    __lowerCAmelCase   ,    bias=__lowerCAmelCase						)
						lowerCamelCase__         =  emb.weight.data
						return lin_layer
def 						A__			(				__lowerCAmelCase		:			Dict						):
						lowerCamelCase__         =  torch.load(__lowerCAmelCase   ,    map_location="""cpu"""						)
						lowerCamelCase__         =  mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""]
						lowerCamelCase__         =  mam_aaa["""model"""]
						remove_ignore_keys_(__lowerCAmelCase						)
						lowerCamelCase__         =  state_dict["""encoder.embed_tokens.weight"""].shape[0]

						lowerCamelCase__         =  MaMaaaConfig(
						    vocab_size=__lowerCAmelCase   ,    max_position_embeddings=1024   ,    encoder_layers=args.encoder_layers   ,    decoder_layers=args.decoder_layers   ,    encoder_attention_heads=args.encoder_attention_heads   ,    decoder_attention_heads=args.decoder_attention_heads   ,    encoder_ffn_dim=args.encoder_ffn_embed_dim   ,    decoder_ffn_dim=args.decoder_ffn_embed_dim   ,    d_model=args.encoder_embed_dim   ,    encoder_layerdrop=args.encoder_layerdrop   ,    decoder_layerdrop=args.decoder_layerdrop   ,    dropout=args.dropout   ,    attention_dropout=args.attention_dropout   ,    activation_dropout=args.activation_dropout   ,    activation_function="""relu"""   ,    )

						lowerCamelCase__         =  state_dict["""decoder.embed_tokens.weight"""]
						lowerCamelCase__         =  MaMaaaForConditionalGeneration(__lowerCAmelCase						)
						model.model.load_state_dict(__lowerCAmelCase   ,    strict=__lowerCAmelCase						)
						lowerCamelCase__         =  make_linear_from_emb(model.model.shared						)

						return model


if __name__ == "__main__":
							UpperCamelCase    :      Optional[Any]  			=		argparse.ArgumentParser()
							# Required parameters
							parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.')
							parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
							UpperCamelCase    :      Tuple  			=		parser.parse_args()
							UpperCamelCase    :      List[Any]  			=		convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß)
							model.save_pretrained(args.pytorch_dump_folder_path)

