





from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool


lowercase      :       Union[str, Any]									=  {
    '''Acehnese Arabic''': '''ace_Arab''',
    '''Acehnese Latin''': '''ace_Latn''',
    '''Mesopotamian Arabic''': '''acm_Arab''',
    '''Ta\'izzi-Adeni Arabic''': '''acq_Arab''',
    '''Tunisian Arabic''': '''aeb_Arab''',
    '''Afrikaans''': '''afr_Latn''',
    '''South Levantine Arabic''': '''ajp_Arab''',
    '''Akan''': '''aka_Latn''',
    '''Amharic''': '''amh_Ethi''',
    '''North Levantine Arabic''': '''apc_Arab''',
    '''Modern Standard Arabic''': '''arb_Arab''',
    '''Modern Standard Arabic Romanized''': '''arb_Latn''',
    '''Najdi Arabic''': '''ars_Arab''',
    '''Moroccan Arabic''': '''ary_Arab''',
    '''Egyptian Arabic''': '''arz_Arab''',
    '''Assamese''': '''asm_Beng''',
    '''Asturian''': '''ast_Latn''',
    '''Awadhi''': '''awa_Deva''',
    '''Central Aymara''': '''ayr_Latn''',
    '''South Azerbaijani''': '''azb_Arab''',
    '''North Azerbaijani''': '''azj_Latn''',
    '''Bashkir''': '''bak_Cyrl''',
    '''Bambara''': '''bam_Latn''',
    '''Balinese''': '''ban_Latn''',
    '''Belarusian''': '''bel_Cyrl''',
    '''Bemba''': '''bem_Latn''',
    '''Bengali''': '''ben_Beng''',
    '''Bhojpuri''': '''bho_Deva''',
    '''Banjar Arabic''': '''bjn_Arab''',
    '''Banjar Latin''': '''bjn_Latn''',
    '''Standard Tibetan''': '''bod_Tibt''',
    '''Bosnian''': '''bos_Latn''',
    '''Buginese''': '''bug_Latn''',
    '''Bulgarian''': '''bul_Cyrl''',
    '''Catalan''': '''cat_Latn''',
    '''Cebuano''': '''ceb_Latn''',
    '''Czech''': '''ces_Latn''',
    '''Chokwe''': '''cjk_Latn''',
    '''Central Kurdish''': '''ckb_Arab''',
    '''Crimean Tatar''': '''crh_Latn''',
    '''Welsh''': '''cym_Latn''',
    '''Danish''': '''dan_Latn''',
    '''German''': '''deu_Latn''',
    '''Southwestern Dinka''': '''dik_Latn''',
    '''Dyula''': '''dyu_Latn''',
    '''Dzongkha''': '''dzo_Tibt''',
    '''Greek''': '''ell_Grek''',
    '''English''': '''eng_Latn''',
    '''Esperanto''': '''epo_Latn''',
    '''Estonian''': '''est_Latn''',
    '''Basque''': '''eus_Latn''',
    '''Ewe''': '''ewe_Latn''',
    '''Faroese''': '''fao_Latn''',
    '''Fijian''': '''fij_Latn''',
    '''Finnish''': '''fin_Latn''',
    '''Fon''': '''fon_Latn''',
    '''French''': '''fra_Latn''',
    '''Friulian''': '''fur_Latn''',
    '''Nigerian Fulfulde''': '''fuv_Latn''',
    '''Scottish Gaelic''': '''gla_Latn''',
    '''Irish''': '''gle_Latn''',
    '''Galician''': '''glg_Latn''',
    '''Guarani''': '''grn_Latn''',
    '''Gujarati''': '''guj_Gujr''',
    '''Haitian Creole''': '''hat_Latn''',
    '''Hausa''': '''hau_Latn''',
    '''Hebrew''': '''heb_Hebr''',
    '''Hindi''': '''hin_Deva''',
    '''Chhattisgarhi''': '''hne_Deva''',
    '''Croatian''': '''hrv_Latn''',
    '''Hungarian''': '''hun_Latn''',
    '''Armenian''': '''hye_Armn''',
    '''Igbo''': '''ibo_Latn''',
    '''Ilocano''': '''ilo_Latn''',
    '''Indonesian''': '''ind_Latn''',
    '''Icelandic''': '''isl_Latn''',
    '''Italian''': '''ita_Latn''',
    '''Javanese''': '''jav_Latn''',
    '''Japanese''': '''jpn_Jpan''',
    '''Kabyle''': '''kab_Latn''',
    '''Jingpho''': '''kac_Latn''',
    '''Kamba''': '''kam_Latn''',
    '''Kannada''': '''kan_Knda''',
    '''Kashmiri Arabic''': '''kas_Arab''',
    '''Kashmiri Devanagari''': '''kas_Deva''',
    '''Georgian''': '''kat_Geor''',
    '''Central Kanuri Arabic''': '''knc_Arab''',
    '''Central Kanuri Latin''': '''knc_Latn''',
    '''Kazakh''': '''kaz_Cyrl''',
    '''Kabiyè''': '''kbp_Latn''',
    '''Kabuverdianu''': '''kea_Latn''',
    '''Khmer''': '''khm_Khmr''',
    '''Kikuyu''': '''kik_Latn''',
    '''Kinyarwanda''': '''kin_Latn''',
    '''Kyrgyz''': '''kir_Cyrl''',
    '''Kimbundu''': '''kmb_Latn''',
    '''Northern Kurdish''': '''kmr_Latn''',
    '''Kikongo''': '''kon_Latn''',
    '''Korean''': '''kor_Hang''',
    '''Lao''': '''lao_Laoo''',
    '''Ligurian''': '''lij_Latn''',
    '''Limburgish''': '''lim_Latn''',
    '''Lingala''': '''lin_Latn''',
    '''Lithuanian''': '''lit_Latn''',
    '''Lombard''': '''lmo_Latn''',
    '''Latgalian''': '''ltg_Latn''',
    '''Luxembourgish''': '''ltz_Latn''',
    '''Luba-Kasai''': '''lua_Latn''',
    '''Ganda''': '''lug_Latn''',
    '''Luo''': '''luo_Latn''',
    '''Mizo''': '''lus_Latn''',
    '''Standard Latvian''': '''lvs_Latn''',
    '''Magahi''': '''mag_Deva''',
    '''Maithili''': '''mai_Deva''',
    '''Malayalam''': '''mal_Mlym''',
    '''Marathi''': '''mar_Deva''',
    '''Minangkabau Arabic ''': '''min_Arab''',
    '''Minangkabau Latin''': '''min_Latn''',
    '''Macedonian''': '''mkd_Cyrl''',
    '''Plateau Malagasy''': '''plt_Latn''',
    '''Maltese''': '''mlt_Latn''',
    '''Meitei Bengali''': '''mni_Beng''',
    '''Halh Mongolian''': '''khk_Cyrl''',
    '''Mossi''': '''mos_Latn''',
    '''Maori''': '''mri_Latn''',
    '''Burmese''': '''mya_Mymr''',
    '''Dutch''': '''nld_Latn''',
    '''Norwegian Nynorsk''': '''nno_Latn''',
    '''Norwegian Bokmål''': '''nob_Latn''',
    '''Nepali''': '''npi_Deva''',
    '''Northern Sotho''': '''nso_Latn''',
    '''Nuer''': '''nus_Latn''',
    '''Nyanja''': '''nya_Latn''',
    '''Occitan''': '''oci_Latn''',
    '''West Central Oromo''': '''gaz_Latn''',
    '''Odia''': '''ory_Orya''',
    '''Pangasinan''': '''pag_Latn''',
    '''Eastern Panjabi''': '''pan_Guru''',
    '''Papiamento''': '''pap_Latn''',
    '''Western Persian''': '''pes_Arab''',
    '''Polish''': '''pol_Latn''',
    '''Portuguese''': '''por_Latn''',
    '''Dari''': '''prs_Arab''',
    '''Southern Pashto''': '''pbt_Arab''',
    '''Ayacucho Quechua''': '''quy_Latn''',
    '''Romanian''': '''ron_Latn''',
    '''Rundi''': '''run_Latn''',
    '''Russian''': '''rus_Cyrl''',
    '''Sango''': '''sag_Latn''',
    '''Sanskrit''': '''san_Deva''',
    '''Santali''': '''sat_Olck''',
    '''Sicilian''': '''scn_Latn''',
    '''Shan''': '''shn_Mymr''',
    '''Sinhala''': '''sin_Sinh''',
    '''Slovak''': '''slk_Latn''',
    '''Slovenian''': '''slv_Latn''',
    '''Samoan''': '''smo_Latn''',
    '''Shona''': '''sna_Latn''',
    '''Sindhi''': '''snd_Arab''',
    '''Somali''': '''som_Latn''',
    '''Southern Sotho''': '''sot_Latn''',
    '''Spanish''': '''spa_Latn''',
    '''Tosk Albanian''': '''als_Latn''',
    '''Sardinian''': '''srd_Latn''',
    '''Serbian''': '''srp_Cyrl''',
    '''Swati''': '''ssw_Latn''',
    '''Sundanese''': '''sun_Latn''',
    '''Swedish''': '''swe_Latn''',
    '''Swahili''': '''swh_Latn''',
    '''Silesian''': '''szl_Latn''',
    '''Tamil''': '''tam_Taml''',
    '''Tatar''': '''tat_Cyrl''',
    '''Telugu''': '''tel_Telu''',
    '''Tajik''': '''tgk_Cyrl''',
    '''Tagalog''': '''tgl_Latn''',
    '''Thai''': '''tha_Thai''',
    '''Tigrinya''': '''tir_Ethi''',
    '''Tamasheq Latin''': '''taq_Latn''',
    '''Tamasheq Tifinagh''': '''taq_Tfng''',
    '''Tok Pisin''': '''tpi_Latn''',
    '''Tswana''': '''tsn_Latn''',
    '''Tsonga''': '''tso_Latn''',
    '''Turkmen''': '''tuk_Latn''',
    '''Tumbuka''': '''tum_Latn''',
    '''Turkish''': '''tur_Latn''',
    '''Twi''': '''twi_Latn''',
    '''Central Atlas Tamazight''': '''tzm_Tfng''',
    '''Uyghur''': '''uig_Arab''',
    '''Ukrainian''': '''ukr_Cyrl''',
    '''Umbundu''': '''umb_Latn''',
    '''Urdu''': '''urd_Arab''',
    '''Northern Uzbek''': '''uzn_Latn''',
    '''Venetian''': '''vec_Latn''',
    '''Vietnamese''': '''vie_Latn''',
    '''Waray''': '''war_Latn''',
    '''Wolof''': '''wol_Latn''',
    '''Xhosa''': '''xho_Latn''',
    '''Eastern Yiddish''': '''ydd_Hebr''',
    '''Yoruba''': '''yor_Latn''',
    '''Yue Chinese''': '''yue_Hant''',
    '''Chinese Simplified''': '''zho_Hans''',
    '''Chinese Traditional''': '''zho_Hant''',
    '''Standard Malay''': '''zsm_Latn''',
    '''Zulu''': '''zul_Latn''',
}





class  A__    (							_A	):




   """simple docstring"""



   __A   :				Dict         =  "facebook/nllb-200-distilled-600M"
   __A   :				List[str]         =  (
       "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should "
       "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, "
       "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in "
       "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`."
   )
   __A   :				List[str]         =  "translator"
   __A   :				str         =  AutoTokenizer
   __A   :				Any         =  AutoModelForSeqaSeqLM
   __A   :				str         =  LANGUAGE_CODES

   __A   :				str         =  ["text", "text", "text"]
   __A   :				Any         =  ["text"]

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						List[str]:







          '''simple docstring'''

          if src_lang not in self.lang_to_code:
                 raise ValueError(F'{src_lang} is not a supported language.')
          if tgt_lang not in self.lang_to_code:
                 raise ValueError(F'{tgt_lang} is not a supported language.')
          a__						:	str =				self.lang_to_code[src_lang]
          a__						:	Union[str, Any] =				self.lang_to_code[tgt_lang]
          return self.pre_processor._build_translation_inputs(
              lowercase					,  return_tensors='pt'					,  src_lang=lowercase					,  tgt_lang=lowercase)

   def 							__lowercase		(					self					,  lowercase)			->						List[str]:







          '''simple docstring'''

          return self.model.generate(**lowercase)

   def 							__lowercase		(					self					,  lowercase)			->						List[str]:







          '''simple docstring'''

          return self.post_processor.decode(outputs[0].tolist()					,  skip_special_tokens=lowercase)










"""simple docstring"""



from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


__A		:       Union[str, Any]  				=		logging.get_logger(__name__)


# General docstring
__A		:       Tuple  				=		'''MobileNetV1Config'''

# Base docstring
__A		:       Union[str, Any]  				=		'''google/mobilenet_v1_1.0_224'''
__A		:       Union[str, Any]  				=		[1, 1_024, 7, 7]

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


__A		:       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 						lowercase    (				__snake_case				: List[str]		,					__snake_case				: Union[str, Any]		,					__snake_case				: Dict=None	):
		lowercase_ : str							       =   {}

		if isinstance(__snake_case		,					__snake_case	):
				lowercase_ : Union[str, Any]							       =   model.mobilenet_va
		else:
				lowercase_ : Optional[Any]							       =   model

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

		for i in range(1_3	):
				lowercase_ : Optional[int]							       =   i + 1
				lowercase_ : Union[str, Any]							       =   i * 2

				lowercase_ : Optional[Any]							       =   backbone.layer[pt_index]
				lowercase_ : Union[str, Any]							       =   F'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
				lowercase_ : str							       =   pointer.convolution.weight
				lowercase_ : int							       =   pointer.normalization.bias
				lowercase_ : Any							       =   pointer.normalization.weight
				lowercase_ : Dict							       =   pointer.normalization.running_mean
				lowercase_ : Union[str, Any]							       =   pointer.normalization.running_var

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

		if isinstance(__snake_case		,					__snake_case	):
				lowercase_ : Optional[Any]							       =   '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
				lowercase_ : Any							       =   model.classifier.weight
				lowercase_ : Optional[int]							       =   model.classifier.bias

		return tf_to_pt_map



def 						lowercase    (				__snake_case				: Optional[int]		,					__snake_case				: int		,					__snake_case				: 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
		lowercase_ : Tuple							       =   tf.train.list_variables(__snake_case	)
		lowercase_ : int							       =   {}
		for name, shape in init_vars:
				logger.info(F'''Loading TF weight {name} with shape {shape}'''	)
				lowercase_ : Optional[Any]							       =   tf.train.load_variable(__snake_case		,					__snake_case	)
				lowercase_ : Optional[int]							       =   array

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

				lowercase_ : Union[str, Any]							       =   tf_weights[name]

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

				tf_weights.pop(__snake_case		,					__snake_case	)
				tf_weights.pop(name + '''/RMSProp'''		,					__snake_case	)
				tf_weights.pop(name + '''/RMSProp_1'''		,					__snake_case	)
				tf_weights.pop(name + '''/ExponentialMovingAverage'''		,					__snake_case	)

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



def 						lowercase    (				__snake_case				: torch.Tensor		,					__snake_case				: nn.Convad	):
		lowercase_       ,					lowercase_ : Optional[int]							       =   features.shape[-2:]
		lowercase_       ,					lowercase_ : str							       =   conv_layer.stride
		lowercase_       ,					lowercase_ : Tuple							       =   conv_layer.kernel_size

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

		if in_width % stride_width == 0:
				lowercase_ : str							       =   max(kernel_width - stride_width		,					0	)
		else:
				lowercase_ : int							       =   max(kernel_width - (in_width % stride_width)		,					0	)

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

		lowercase_ : str							       =   (pad_left, pad_right, pad_top, pad_bottom)
		return nn.functional.pad(__snake_case		,					__snake_case		,					'''constant'''		,					0.0	)





class 					_UpperCAmelCase       ( nn.Module							):




					def __init__(				self     :						List[Any]    ,						A     :						MobileNetVaConfig    ,						A     :						int    ,						A     :						int    ,						A     :						int    ,						A     :						Optional[int] = 1    ,						A     :						Optional[int] = 1    ,						A     :						bool = False    ,						A     :						Optional[bool] = True    ,						A     :						Optional[bool or str] = True    ,						)  ->  None:
							super().__init__()
							lowercase_ : int							       =   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.'''   )

							lowercase_ : Tuple							       =   0 if config.tf_padding else int((kernel_size - 1) / 2   )

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

							if use_activation:
									if isinstance(A    ,						A   ):
											lowercase_ : str							       =   ACTaFN[use_activation]
									elif isinstance(config.hidden_act    ,						A   ):
											lowercase_ : Any							       =   ACTaFN[config.hidden_act]
									else:
											lowercase_ : Tuple							       =   config.hidden_act
							else:
									lowercase_ : Tuple							       =   None






					def   A  (				self     :						str    ,						A     :						torch.Tensor   )  ->  torch.Tensor:
							if self.config.tf_padding:
									lowercase_ : List[Any]							       =   apply_tf_padding(A    ,						self.convolution   )
							lowercase_ : Optional[int]							       =   self.convolution(A   )
							if self.normalization is not None:
									lowercase_ : Union[str, Any]							       =   self.normalization(A   )
							if self.activation is not None:
									lowercase_ : Optional[int]							       =   self.activation(A   )
							return features





class 					_UpperCAmelCase       ( _A							):
					SCREAMING_SNAKE_CASE_		:				Optional[int]							    =   MobileNetVaConfig
					SCREAMING_SNAKE_CASE_		:				int							    =   load_tf_weights_in_mobilenet_va
					SCREAMING_SNAKE_CASE_		:				Optional[Any]							    =   "mobilenet_v1"
					SCREAMING_SNAKE_CASE_		:				Union[str, Any]							    =   "pixel_values"
					SCREAMING_SNAKE_CASE_		:				List[str]							    =   False




					def   A  (				self     :						Any    ,						A     :						Union[nn.Linear, nn.Convad]   )  ->  None:
							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   )
__A		:       Union[str, Any]  				=		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.
'''

__A		:       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     :						str    ,						A     :						MobileNetVaConfig    ,						A     :						bool = True   )  ->  int:
							super().__init__(A   )
							lowercase_ : Union[str, Any]							       =   config

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

							lowercase_ : Union[str, Any]							       =   MobileNetVaConvLayer(
							    A    ,						in_channels=config.num_channels    ,						out_channels=A    ,						kernel_size=3    ,						stride=2    ,						)

							lowercase_ : Optional[Any]							       =   [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

							lowercase_ : List[Any]							       =   nn.ModuleList()
							for i in range(13   ):
									lowercase_ : Dict							       =   out_channels

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

							lowercase_ : int							       =   nn.AdaptiveAvgPoolad((1, 1)   ) if add_pooling_layer else None

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




					def   A  (				self     :						Any    ,						A     :						Optional[Any]   )  ->  Optional[int]:
							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   A  (				self     :						List[Any]    ,						A     :						Optional[torch.Tensor] = None    ,						A     :						Optional[bool] = None    ,						A     :						Optional[bool] = None    ,						)  ->  Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
							lowercase_ : str							       =   (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							lowercase_ : Union[str, 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'''   )

							lowercase_ : List[str]							       =   self.conv_stem(A   )

							lowercase_ : Dict							       =   () if output_hidden_states else None

							for i, layer_module in enumerate(self.layer   ):
									lowercase_ : Optional[int]							       =   layer_module(A   )

									if output_hidden_states:
											lowercase_ : str							       =   all_hidden_states + (hidden_states,)

							lowercase_ : Tuple							       =   hidden_states

							if self.pooler is not None:
									lowercase_ : Dict							       =   torch.flatten(self.pooler(A   )    ,						start_dim=1   )
							else:
									lowercase_ : Optional[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=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    "   ,						_A   ,						)
class 					_UpperCAmelCase       ( _A							):




					def __init__(				self     :						List[str]    ,						A     :						MobileNetVaConfig   )  ->  None:
							super().__init__(A   )

							lowercase_ : int							       =   config.num_labels
							lowercase_ : List[str]							       =   MobileNetVaModel(A   )

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

							# Classifier head
							lowercase_ : Tuple							       =   nn.Dropout(config.classifier_dropout_prob    ,						inplace=A   )
							lowercase_ : int							       =   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   A  (				self     :						Optional[Any]    ,						A     :						Optional[torch.Tensor] = None    ,						A     :						Optional[bool] = None    ,						A     :						Optional[torch.Tensor] = None    ,						A     :						Optional[bool] = None    ,						)  ->  Union[tuple, ImageClassifierOutputWithNoAttention]:
							lowercase_ : Union[str, Any]							       =   return_dict if return_dict is not None else self.config.use_return_dict

							lowercase_ : List[Any]							       =   self.mobilenet_va(A    ,						output_hidden_states=A    ,						return_dict=A   )

							lowercase_ : Union[str, Any]							       =   outputs.pooler_output if return_dict else outputs[1]

							lowercase_ : Dict							       =   self.classifier(self.dropout(A   )   )

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

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

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

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



