





import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


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

lowercase      :       List[str]									=  '''▁'''

lowercase      :       Any									=  {'''vocab_file''': '''sentencepiece.bpe.model'''}

lowercase      :       Union[str, Any]									=  {
    '''vocab_file''': {
        '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''',
        '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''',
        '''xlm-roberta-large-finetuned-conll02-dutch''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll02-spanish''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll03-english''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll03-german''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model'''
        ),
    }
}

lowercase      :       Optional[Any]									=  {
    '''xlm-roberta-base''': 5_1_2,
    '''xlm-roberta-large''': 5_1_2,
    '''xlm-roberta-large-finetuned-conll02-dutch''': 5_1_2,
    '''xlm-roberta-large-finetuned-conll02-spanish''': 5_1_2,
    '''xlm-roberta-large-finetuned-conll03-english''': 5_1_2,
    '''xlm-roberta-large-finetuned-conll03-german''': 5_1_2,
}





class  A__    (							_A	):




   """simple docstring"""



   __A   :				Dict         =  VOCAB_FILES_NAMES
   __A   :				Union[str, Any]         =  PRETRAINED_VOCAB_FILES_MAP
   __A   :				str         =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __A   :				Tuple         =  ["input_ids", "attention_mask"]

   def __init__(					self					,  lowercase					,  lowercase="<s>"					,  lowercase="</s>"					,  lowercase="</s>"					,  lowercase="<s>"					,  lowercase="<unk>"					,  lowercase="<pad>"					,  lowercase="<mask>"					,  lowercase = None					,  **lowercase					,  )			->						None:







          '''simple docstring'''

          a__						:	Any =				AddedToken(lowercase					,  lstrip=lowercase					,  rstrip=lowercase) if isinstance(lowercase					,  lowercase) else mask_token

          a__						:	Optional[int] =				{} if sp_model_kwargs is None else sp_model_kwargs

          super().__init__(
              bos_token=lowercase					,  eos_token=lowercase					,  unk_token=lowercase					,  sep_token=lowercase					,  cls_token=lowercase					,  pad_token=lowercase					,  mask_token=lowercase					,  sp_model_kwargs=self.sp_model_kwargs					,  **lowercase					,  )

          a__						:	int =				spm.SentencePieceProcessor(**self.sp_model_kwargs)
          self.sp_model.Load(str(lowercase))
          a__						:	Optional[Any] =				vocab_file

          # Original fairseq vocab and spm vocab must be "aligned":
          # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
          # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
          # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
          # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

          # Mimic fairseq token-to-id alignment for the first 4 token
          a__						:	List[Any] =				{'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

          # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
          a__						:	List[Any] =				1

          a__						:	Tuple =				len(self.sp_model) + self.fairseq_offset
          a__						:	Optional[int] =				{v: k for k, v in self.fairseq_tokens_to_ids.items()}

   def __getstate__(					self)			->						Dict:







          '''simple docstring'''

          a__						:	Tuple =				self.__dict__.copy()
          a__						:	str =				None
          a__						:	str =				self.sp_model.serialized_model_proto()
          return state

   def __setstate__(					self					,  lowercase)			->						int:







          '''simple docstring'''

          a__						:	Optional[int] =				d

          # for backward compatibility
          if not hasattr(self					,  'sp_model_kwargs'):
                 a__						:	Dict =				{}

          a__						:	List[str] =				spm.SentencePieceProcessor(**self.sp_model_kwargs)
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto)

   def 							__lowercase		(					self					,  lowercase					,  lowercase = None)			->						List[int]:







          '''simple docstring'''

          if token_ids_a is None:
                 return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
          a__						:	Optional[int] =				[self.cls_token_id]
          a__						:	List[str] =				[self.sep_token_id]
          return cls + token_ids_a + sep + sep + token_ids_a + sep

   def 							__lowercase		(					self					,  lowercase					,  lowercase = None					,  lowercase = False)			->						List[int]:







          '''simple docstring'''

          if already_has_special_tokens:
                 return super().get_special_tokens_mask(
                     token_ids_a=lowercase					,  token_ids_a=lowercase					,  already_has_special_tokens=lowercase)

          if token_ids_a is None:
                 return [1] + ([0] * len(lowercase)) + [1]
          return [1] + ([0] * len(lowercase)) + [1, 1] + ([0] * len(lowercase)) + [1]

   def 							__lowercase		(					self					,  lowercase					,  lowercase = None)			->						List[int]:







          '''simple docstring'''

          a__						:	str =				[self.sep_token_id]
          a__						:	List[Any] =				[self.cls_token_id]

          if token_ids_a is None:
                 return len(cls + token_ids_a + sep) * [0]
          return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]

   @property
   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          return len(self.sp_model) + self.fairseq_offset + 1  # Add the <mask> token

   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          a__						:	List[str] =				{self.convert_ids_to_tokens(lowercase): i for i in range(self.vocab_size)}
          vocab.update(self.added_tokens_encoder)
          return vocab

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







          '''simple docstring'''

          return self.sp_model.encode(lowercase					,  out_type=lowercase)

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







          '''simple docstring'''

          if token in self.fairseq_tokens_to_ids:
                 return self.fairseq_tokens_to_ids[token]
          a__						:	Dict =				self.sp_model.PieceToId(lowercase)

          # Need to return unknown token if the SP model returned 0
          return spm_id + self.fairseq_offset if spm_id else self.unk_token_id

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







          '''simple docstring'''

          if index in self.fairseq_ids_to_tokens:
                 return self.fairseq_ids_to_tokens[index]
          return self.sp_model.IdToPiece(index - self.fairseq_offset)

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







          '''simple docstring'''

          a__						:	Tuple =				''''''.join(lowercase).replace(lowercase					,  ' ').strip()
          return out_string

   def 							__lowercase		(					self					,  lowercase					,  lowercase = None)			->						Tuple[str]:







          '''simple docstring'''

          if not os.path.isdir(lowercase):
                 logger.error(F'Vocabulary path ({save_directory}) should be a directory')
                 return
          a__						:	int =				os.path.join(
              lowercase					,  (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])

          if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase) and os.path.isfile(self.vocab_file):
                 copyfile(self.vocab_file					,  lowercase)
          elif not os.path.isfile(self.vocab_file):
                 with open(lowercase					,  'wb') as fi:
                        a__						:	Optional[Any] =				self.sp_model.serialized_model_proto()
                        fi.write(lowercase)

          return (out_vocab_file,)










"""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    ,						)



