


import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    WavaVecaConfig,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaForPreTraining,
    WavaVecaProcessor,
    logging,
)
from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification


logging.set_verbosity_info()
__snake_case   							=						logging.get_logger(__name__)

__snake_case   							=						{
    '''post_extract_proj''': '''feature_projection.projection''',
    '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''',
    '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''',
    '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''',
    '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''',
    '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''',
    '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''',
    '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''',
    '''fc2''': '''encoder.layers.*.feed_forward.output_dense''',
    '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''',
    '''encoder.layer_norm''': '''encoder.layer_norm''',
    '''adapter_layer''': '''encoder.layers.*.adapter_layer''',
    '''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
    '''quantizer.weight_proj''': '''quantizer.weight_proj''',
    '''quantizer.vars''': '''quantizer.codevectors''',
    '''project_q''': '''project_q''',
    '''final_proj''': '''project_hid''',
    '''w2v_encoder.proj''': '''lm_head''',
    '''mask_emb''': '''masked_spec_embed''',
    '''pooling_layer.linear''': '''projector''',
    '''pooling_layer.projection''': '''classifier''',
}
__snake_case   							=						[
    '''lm_head''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
    '''projector''',
    '''classifier''',
]






def 		_A		(		_lowercase )					-> Optional[Any]:


     """simple docstring"""


     __UpperCamelCase =			{}
     with open(_lowercase					,  'r' ) as file:
          for line_number, line in enumerate(_lowercase ):
               __UpperCamelCase =			line.strip()
               if line:
                    __UpperCamelCase =			line.split()
                    __UpperCamelCase =			line_number
                    __UpperCamelCase =			words[0]
                    __UpperCamelCase =			value
     return result






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase					,  _lowercase					,  _lowercase )					-> List[str]:


     """simple docstring"""


     for attribute in key.split('.' ):
          __UpperCamelCase =			getattr(_lowercase					,  _lowercase )

     __UpperCamelCase =			None
     for param_key in PARAM_MAPPING.keys():
          if full_name.endswith(_lowercase ):
               __UpperCamelCase =			PARAM_MAPPING[full_name.split('.' )[-1]]
               __UpperCamelCase =			'param'

     if weight_type is not None and weight_type != "param":
          __UpperCamelCase =			getattr(_lowercase					,  _lowercase ).shape
     elif weight_type is not None and weight_type == "param":
          __UpperCamelCase =			hf_pointer
          for attribute in hf_param_name.split('.' ):
               __UpperCamelCase =			getattr(_lowercase					,  _lowercase )
          __UpperCamelCase =			shape_pointer.shape

          # let's reduce dimension
          __UpperCamelCase =			value[0]
     else:
          __UpperCamelCase =			hf_pointer.shape

     if hf_shape != value.shape:
          raise ValueError(
              f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
              f''' {value.shape} for {full_name}''' )

     if weight_type == "weight":
          __UpperCamelCase =			value
     elif weight_type == "weight_g":
          __UpperCamelCase =			value
     elif weight_type == "weight_v":
          __UpperCamelCase =			value
     elif weight_type == "bias":
          __UpperCamelCase =			value
     elif weight_type == "param":
          for attribute in hf_param_name.split('.' ):
               __UpperCamelCase =			getattr(_lowercase					,  _lowercase )
          __UpperCamelCase =			value
     else:
          __UpperCamelCase =			value

     logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase					,  _lowercase					,  _lowercase )					-> List[Any]:


     """simple docstring"""


     __UpperCamelCase =			None
     for param_key in PARAM_MAPPING.keys():
          if full_name.endswith(_lowercase ):
               __UpperCamelCase =			PARAM_MAPPING[full_name.split('.' )[-1]]
               __UpperCamelCase =			'param'

     if weight_type is not None and weight_type != "param":
          __UpperCamelCase =			'.'.join([key, weight_type] )
     elif weight_type is not None and weight_type == "param":
          __UpperCamelCase =			'.'.join([key, hf_param_name] )
     else:
          __UpperCamelCase =			key

     __UpperCamelCase =			value if 'lm_head' in full_key else value[0]


__snake_case   							=						{
    '''W_a''': '''linear_1.weight''',
    '''W_b''': '''linear_2.weight''',
    '''b_a''': '''linear_1.bias''',
    '''b_b''': '''linear_2.bias''',
    '''ln_W''': '''norm.weight''',
    '''ln_b''': '''norm.bias''',
}






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase=None					,  _lowercase=None )					-> List[Any]:


     """simple docstring"""


     __UpperCamelCase =			False
     for key, mapped_key in MAPPING.items():
          __UpperCamelCase =			'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
          if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
               __UpperCamelCase =			True
               if "*" in mapped_key:
                    __UpperCamelCase =			name.split(_lowercase )[0].split('.' )[-2]
                    __UpperCamelCase =			mapped_key.replace('*'					,  _lowercase )
               if "weight_g" in name:
                    __UpperCamelCase =			'weight_g'
               elif "weight_v" in name:
                    __UpperCamelCase =			'weight_v'
               elif "bias" in name:
                    __UpperCamelCase =			'bias'
               elif "weight" in name:
                    # TODO: don't match quantizer.weight_proj
                    __UpperCamelCase =			'weight'
               else:
                    __UpperCamelCase =			None
               if hf_dict is not None:
                    rename_dict(_lowercase					,  _lowercase					,  _lowercase					,  _lowercase					,  _lowercase )
               else:
                    set_recursively(_lowercase					,  _lowercase					,  _lowercase					,  _lowercase					,  _lowercase )
               return is_used
     return is_used






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase )					-> Dict:


     """simple docstring"""


     __UpperCamelCase =			[]
     __UpperCamelCase =			fairseq_model.state_dict()

     __UpperCamelCase =			hf_model.wavaveca.feature_extractor

     for name, value in fairseq_dict.items():
          __UpperCamelCase =			False
          if "conv_layers" in name:
               load_conv_layer(
                   _lowercase					,  _lowercase					,  _lowercase					,  _lowercase					,  hf_model.config.feat_extract_norm == 'group'					,  )
               __UpperCamelCase =			True
          else:
               __UpperCamelCase =			load_wavaveca_layer(_lowercase					,  _lowercase					,  _lowercase )
          if not is_used:
               unused_weights.append(_lowercase )

     logger.warning(f'''Unused weights: {unused_weights}''' )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase					,  _lowercase					,  _lowercase )					-> Any:


     """simple docstring"""


     __UpperCamelCase =			full_name.split('conv_layers.' )[-1]
     __UpperCamelCase =			name.split('.' )
     __UpperCamelCase =			int(items[0] )
     __UpperCamelCase =			int(items[1] )

     if type_id == 0:
          if "bias" in name:
               if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
                    raise ValueError(
                        f'''{full_name} has size {value.shape}, but'''
                        f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' )
               __UpperCamelCase =			value
               logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
          elif "weight" in name:
               if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
                    raise ValueError(
                        f'''{full_name} has size {value.shape}, but'''
                        f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' )
               __UpperCamelCase =			value
               logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
     elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
          if "bias" in name:
               if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
                    raise ValueError(
                        f'''{full_name} has size {value.shape}, but'''
                        f''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' )
               __UpperCamelCase =			value
               logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
          elif "weight" in name:
               if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
                    raise ValueError(
                        f'''{full_name} has size {value.shape}, but'''
                        f''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' )
               __UpperCamelCase =			value
               logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
     else:
          unused_weights.append(_lowercase )






@torch.no_grad()
def 		_A		(		_lowercase					,  _lowercase					,  _lowercase=None					,  _lowercase=None					,  _lowercase=True					,  _lowercase=False )					-> Dict:


     """simple docstring"""


     if config_path is not None:
          __UpperCamelCase =			WavaVecaConfig.from_pretrained(_lowercase )
     else:
          __UpperCamelCase =			WavaVecaConfig()

     if is_seq_class:
          __UpperCamelCase =			read_txt_into_dict(_lowercase )
          __UpperCamelCase =			idalabel
          __UpperCamelCase =			WavaVecaForSequenceClassification(_lowercase )
          __UpperCamelCase =			WavaVecaFeatureExtractor(
              feature_size=1					,  sampling_rate=1_60_00					,  padding_value=0					,  do_normalize=_lowercase					,  return_attention_mask=_lowercase					,  )
          feature_extractor.save_pretrained(_lowercase )

     elif is_finetuned:
          if dict_path:
               __UpperCamelCase =			Dictionary.load(_lowercase )

               # important change bos & pad token id since CTC symbol is <pad> and
               # not <s> as in fairseq
               __UpperCamelCase =			target_dict.pad_index
               __UpperCamelCase =			target_dict.bos_index
               __UpperCamelCase =			target_dict.eos_index
               __UpperCamelCase =			len(target_dict.symbols )
               __UpperCamelCase =			os.path.join(_lowercase					,  'vocab.json' )
               if not os.path.isdir(_lowercase ):
                    logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(_lowercase ) )
                    return
               os.makedirs(_lowercase					,  exist_ok=_lowercase )
               __UpperCamelCase =			target_dict.indices

               # fairseq has the <pad> and <s> switched
               __UpperCamelCase =			0
               __UpperCamelCase =			1
               with open(_lowercase					,  'w'					,  encoding='utf-8' ) as vocab_handle:
                    json.dump(_lowercase					,  _lowercase )
               __UpperCamelCase =			WavaVecaCTCTokenizer(
                   _lowercase					,  unk_token=target_dict.unk_word					,  pad_token=target_dict.pad_word					,  bos_token=target_dict.bos_word					,  eos_token=target_dict.eos_word					,  word_delimiter_token='|'					,  do_lower_case=_lowercase					,  )
               __UpperCamelCase =			True if config.feat_extract_norm == 'layer' else False
               __UpperCamelCase =			WavaVecaFeatureExtractor(
                   feature_size=1					,  sampling_rate=1_60_00					,  padding_value=0					,  do_normalize=_lowercase					,  return_attention_mask=_lowercase					,  )
               __UpperCamelCase =			WavaVecaProcessor(feature_extractor=_lowercase					,  tokenizer=_lowercase )
               processor.save_pretrained(_lowercase )

          __UpperCamelCase =			WavaVecaForCTC(_lowercase )
     else:
          __UpperCamelCase =			WavaVecaForPreTraining(_lowercase )

     if is_finetuned or is_seq_class:
          __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase =			fairseq.checkpoint_utils.load_model_ensemble_and_task(
              [checkpoint_path]					,  arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
     else:
          __UpperCamelCase =			argparse.Namespace(task='audio_pretraining' )
          __UpperCamelCase =			fairseq.tasks.setup_task(_lowercase )

          __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase =			fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]					,  task=_lowercase )

     __UpperCamelCase =			model[0].eval()

     recursively_load_weights(_lowercase					,  _lowercase					,  not is_finetuned )

     hf_wavavec.save_pretrained(_lowercase )


if __name__ == "__main__":
    __snake_case   							=						argparse.ArgumentParser()
    parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
    parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
    parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
    parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
    parser.add_argument(
        '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not'''
    )
    parser.add_argument(
        '''--is_seq_class''',
        action='''store_true''',
        help='''Whether the model to convert is a fine-tuned sequence classification model or not''',
    )
    __snake_case   							=						parser.parse_args()

    __snake_case   							=						not args.not_finetuned and not args.is_seq_class
    convert_wavaveca_checkpoint(
        args.checkpoint_path,
        args.pytorch_dump_folder_path,
        args.config_path,
        args.dict_path,
        is_finetuned,
        args.is_seq_class,
    )







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


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

# Base docstring
_lowerCAmelCase	:   Tuple    =   "google/mobilenet_v1_1.0_224"
_lowerCAmelCase	:   Optional[int]    =   [1, 1_0_2_4, 7, 7]

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


_lowerCAmelCase	:   Tuple    =   [
    "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_		(					snake_case__    ,			snake_case__    ,			snake_case__=None					)	->     Union[str, Any]:



				"""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     UpperCAmelCase_		(					snake_case__    ,			snake_case__    ,			snake_case__					)	->     List[str]:



				"""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     UpperCAmelCase_		(					snake_case__    ,			snake_case__					)	->     torch.Tensor:



				"""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 	__snake_case   ( nn.Module ):
		def __init__(							self    ,a_    ,a_    ,a_    ,a_    ,a_ = 1    ,a_ = 1    ,a_ = False    ,a_ = True    ,a_ = True    ,):







						"""simple docstring"""
						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=a_    ,out_channels=a_    ,kernel_size=a_    ,stride=a_    ,padding=a_    ,groups=a_    ,bias=a_    ,padding_mode='zeros'    ,)

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

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



		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						if self.config.tf_padding:
										lowerCAmelCase__		  =  apply_tf_padding(a_    ,self.convolution						)
						lowerCAmelCase__		  =  self.convolution(a_						)
						if self.normalization is not None:
										lowerCAmelCase__		  =  self.normalization(a_						)
						if self.activation is not None:
										lowerCAmelCase__		  =  self.activation(a_						)
						return features



class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		SCREAMING_SNAKE_CASE__								=	MobileNetVaConfig
		SCREAMING_SNAKE_CASE__								=	load_tf_weights_in_mobilenet_va
		SCREAMING_SNAKE_CASE__								=	'mobilenet_v1'
		SCREAMING_SNAKE_CASE__								=	'pixel_values'
		SCREAMING_SNAKE_CASE__								=	False
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						if isinstance(a_    ,(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(a_    ,nn.BatchNormad						):
										module.bias.data.zero_()
										module.weight.data.fill_(1.0						)



_lowerCAmelCase	:   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"

_lowerCAmelCase	:   Dict    =   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.'							, SCREAMING_SNAKE_CASE							, )
class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		def __init__(							self    ,a_    ,a_ = True						):







						"""simple docstring"""
						super().__init__(a_						)
						lowerCAmelCase__		  =  config

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

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

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

						lowerCAmelCase__		  =  nn.AdaptiveAvgPoolad((1, 1)						) if add_pooling_layer else None

						# Initialize weights and apply final processing
						self.post_init()
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						raise NotImplementedError



		@add_start_docstrings_to_model_forward(a_						)
		@add_code_sample_docstrings(
		    checkpoint=_CHECKPOINT_FOR_DOC    ,output_type=a_    ,config_class=_CONFIG_FOR_DOC    ,modality='vision'    ,expected_output=_EXPECTED_OUTPUT_SHAPE    ,)
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_ = None    ,a_ = None    ,a_ = None    ,):







						"""simple docstring"""
						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(a_						)

						lowerCAmelCase__		  =  () if output_hidden_states else None

						for i, layer_module in enumerate(self.layer						):
										lowerCAmelCase__		  =  layer_module(a_						)

										if output_hidden_states:
														lowerCAmelCase__		  =  all_hidden_states + (hidden_states,)

						lowerCAmelCase__		  =  hidden_states

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



@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    '							, SCREAMING_SNAKE_CASE							, )
class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		def __init__(							self    ,a_						):







						"""simple docstring"""
						super().__init__(a_						)

						lowerCAmelCase__		  =  config.num_labels
						lowerCAmelCase__		  =  MobileNetVaModel(a_						)

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

						# Classifier head
						lowerCAmelCase__		  =  nn.Dropout(config.classifier_dropout_prob    ,inplace=a_						)
						lowerCAmelCase__		  =  nn.Linear(a_    ,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(a_						)
		@add_code_sample_docstrings(
		    checkpoint=_IMAGE_CLASS_CHECKPOINT    ,output_type=a_    ,config_class=_CONFIG_FOR_DOC    ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT    ,)
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_ = None    ,a_ = None    ,a_ = None    ,a_ = None    ,):







						"""simple docstring"""
						lowerCAmelCase__		  =  return_dict if return_dict is not None else self.config.use_return_dict

						lowerCAmelCase__		  =  self.mobilenet_va(a_    ,output_hidden_states=a_    ,return_dict=a_						)

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

						lowerCAmelCase__		  =  self.classifier(self.dropout(a_						)						)

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

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

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