






"""simple docstring"""



from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import TFCvtForImageClassification, TFCvtModel
						from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor





class 					_UpperCAmelCase       ( _A							):




					def   A  (				self     :						str   )  ->  Dict:
							lowercase_ : str							       =   self.config_class(**self.inputs_dict   )
							self.parent.assertTrue(hasattr(A    ,						'''embed_dim'''   )   )
							self.parent.assertTrue(hasattr(A    ,						'''num_heads'''   )   )





class 					_UpperCAmelCase       :




					def __init__(				self     :						Tuple    ,						A     :						Union[str, Any]    ,						A     :						Union[str, Any]=13    ,						A     :						Optional[int]=64    ,						A     :						Optional[int]=3    ,						A     :						Any=[16, 48, 96]    ,						A     :						Any=[1, 3, 6]    ,						A     :						str=[1, 2, 10]    ,						A     :						List[str]=[7, 3, 3]    ,						A     :						Dict=[4, 2, 2]    ,						A     :						List[str]=[2, 1, 1]    ,						A     :						List[Any]=[2, 2, 2]    ,						A     :						List[Any]=[False, False, True]    ,						A     :						str=[0.0, 0.0, 0.0]    ,						A     :						Dict=0.02    ,						A     :						Union[str, Any]=1e-12    ,						A     :						int=True    ,						A     :						Tuple=True    ,						A     :						Any=2    ,						)  ->  Union[str, Any]:
							lowercase_ : str							       =   parent
							lowercase_ : Optional[Any]							       =   batch_size
							lowercase_ : int							       =   image_size
							lowercase_ : Optional[Any]							       =   patch_sizes
							lowercase_ : Tuple							       =   patch_stride
							lowercase_ : List[Any]							       =   patch_padding
							lowercase_ : Optional[int]							       =   is_training
							lowercase_ : Optional[int]							       =   use_labels
							lowercase_ : Optional[Any]							       =   num_labels
							lowercase_ : int							       =   num_channels
							lowercase_ : List[Any]							       =   embed_dim
							lowercase_ : Optional[Any]							       =   num_heads
							lowercase_ : Union[str, Any]							       =   stride_kv
							lowercase_ : str							       =   depth
							lowercase_ : Tuple							       =   cls_token
							lowercase_ : List[str]							       =   attention_drop_rate
							lowercase_ : List[str]							       =   initializer_range
							lowercase_ : Optional[int]							       =   layer_norm_eps




					def   A  (				self     :						str   )  ->  Any:
							lowercase_ : List[str]							       =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

							lowercase_ : Optional[int]							       =   None
							if self.use_labels:
									# create a random int32 tensor of given shape
									lowercase_ : List[str]							       =   ids_tensor([self.batch_size]    ,						self.num_labels   )

							lowercase_ : Any							       =   self.get_config()
							return config, pixel_values, labels




					def   A  (				self     :						Optional[int]   )  ->  Optional[Any]:
							return CvtConfig(
							    image_size=self.image_size    ,						num_labels=self.num_labels    ,						num_channels=self.num_channels    ,						embed_dim=self.embed_dim    ,						num_heads=self.num_heads    ,						patch_sizes=self.patch_sizes    ,						patch_padding=self.patch_padding    ,						patch_stride=self.patch_stride    ,						stride_kv=self.stride_kv    ,						depth=self.depth    ,						cls_token=self.cls_token    ,						attention_drop_rate=self.attention_drop_rate    ,						initializer_range=self.initializer_range    ,						)




					def   A  (				self     :						List[str]    ,						A     :						Dict    ,						A     :						Optional[int]    ,						A     :						Tuple   )  ->  Any:
							lowercase_ : Optional[int]							       =   TFCvtModel(config=A   )
							lowercase_ : Any							       =   model(A    ,						training=A   )
							lowercase_ : List[str]							       =   (self.image_size, self.image_size)
							lowercase_       ,					lowercase_ : Optional[Any]							       =   image_size[0], image_size[1]
							for i in range(len(self.depth   )   ):
									lowercase_ : List[Any]							       =   floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
									lowercase_ : List[Any]							       =   floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
							self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.embed_dim[-1], height, width)   )




					def   A  (				self     :						Tuple    ,						A     :						Optional[int]    ,						A     :						int    ,						A     :						Tuple   )  ->  Any:
							lowercase_ : Any							       =   self.num_labels
							lowercase_ : Union[str, Any]							       =   TFCvtForImageClassification(A   )
							lowercase_ : List[Any]							       =   model(A    ,						labels=A    ,						training=A   )
							self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels)   )






					def   A  (				self     :						Optional[Any]   )  ->  Any:
							lowercase_ : Tuple							       =   self.prepare_config_and_inputs()
							lowercase_       ,					lowercase_       ,					lowercase_ : List[str]							       =   config_and_inputs
							lowercase_ : Union[str, Any]							       =   {'''pixel_values''': pixel_values}
							return config, inputs_dict





@require_tf
class 					_UpperCAmelCase       ( _A   ,						_A   ,						unittest.TestCase							):
					SCREAMING_SNAKE_CASE_		:				Optional[int]							    =   (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
					SCREAMING_SNAKE_CASE_		:				Union[str, Any]							    =   (
					    {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
					    if is_tf_available()
					    else {}
					)
					SCREAMING_SNAKE_CASE_		:				Optional[Any]							    =   False
					SCREAMING_SNAKE_CASE_		:				Dict							    =   False
					SCREAMING_SNAKE_CASE_		:				Dict							    =   False
					SCREAMING_SNAKE_CASE_		:				List[Any]							    =   False
					SCREAMING_SNAKE_CASE_		:				List[str]							    =   False




					def   A  (				self     :						Optional[int]   )  ->  Tuple:
							lowercase_ : Union[str, Any]							       =   TFCvtModelTester(self   )
							lowercase_ : int							       =   TFCvtConfigTester(self    ,						config_class=A    ,						has_text_modality=A    ,						hidden_size=37   )




					def   A  (				self     :						Tuple   )  ->  Dict:
							self.config_tester.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()




					@unittest.skip(reason='''Cvt does not output attentions'''   )
					def   A  (				self     :						Optional[Any]   )  ->  str:
							pass




					@unittest.skip(reason='''Cvt does not use inputs_embeds'''   )
					def   A  (				self     :						Dict   )  ->  Optional[Any]:
							pass




					@unittest.skip(reason='''Cvt does not support input and output embeddings'''   )
					def   A  (				self     :						Tuple   )  ->  Optional[int]:
							pass




					@unittest.skipIf(
					    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''   )   ) == 0    ,						reason='''TF does not support backprop for grouped convolutions on CPU.'''    ,						)
					def   A  (				self     :						List[str]   )  ->  Optional[int]:
							super().test_dataset_conversion()




					@unittest.skipIf(
					    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''   )   ) == 0    ,						reason='''TF does not support backprop for grouped convolutions on CPU.'''    ,						)
					@slow
					def   A  (				self     :						Optional[Any]   )  ->  Union[str, Any]:
							super().test_keras_fit()




					@unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'''   )
					def   A  (				self     :						Optional[int]   )  ->  Optional[int]:
							lowercase_ : Optional[Any]							       =   tf.keras.mixed_precision.Policy('''mixed_float16'''   )
							tf.keras.mixed_precision.set_global_policy(A   )
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy('''float32'''   )




					def   A  (				self     :						Dict   )  ->  List[str]:
							lowercase_       ,					lowercase_ : Any							       =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowercase_ : Optional[Any]							       =   model_class(A   )
									lowercase_ : List[str]							       =   inspect.signature(model.call   )
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									lowercase_ : List[str]							       =   [*signature.parameters.keys()]

									lowercase_ : int							       =   ['''pixel_values''']
									self.assertListEqual(arg_names[:1]    ,						A   )




					def   A  (				self     :						Tuple   )  ->  str:
							def check_hidden_states_output(A     :						Dict    ,						A     :						List[Any]    ,						A     :						Optional[Any]   ):
									lowercase_ : Tuple							       =   model_class(A   )

									lowercase_ : Any							       =   model(**self._prepare_for_class(A    ,						A   )   )
									lowercase_ : Union[str, Any]							       =   outputs.hidden_states

									lowercase_ : Optional[int]							       =   len(self.model_tester.depth   )
									self.assertEqual(len(A   )    ,						A   )

									# verify the first hidden states (first block)
									self.assertListEqual(
									    list(hidden_states[0].shape[-3:]   )    ,						[
									        self.model_tester.embed_dim[0],
									        self.model_tester.image_size // 4,
									        self.model_tester.image_size // 4,
									    ]    ,						)

							lowercase_       ,					lowercase_ : Tuple							       =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowercase_ : Tuple							       =   True
									check_hidden_states_output(A    ,						A    ,						A   )

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									lowercase_ : Any							       =   True

									check_hidden_states_output(A    ,						A    ,						A   )




					def   A  (				self     :						int   )  ->  List[str]:
							lowercase_ : Optional[int]							       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*A   )




					def   A  (				self     :						Optional[int]   )  ->  Optional[Any]:
							lowercase_ : Any							       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*A   )






					@slow
					def   A  (				self     :						Any   )  ->  List[Any]:
							for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowercase_ : Optional[int]							       =   TFCvtModel.from_pretrained(A   )
									self.assertIsNotNone(A   )



def 						lowercase    (				):
		lowercase_ : int							       =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
		return image






@require_tf
@require_vision
class 					_UpperCAmelCase       ( unittest.TestCase							):




					@cached_property
					def   A  (				self     :						List[str]   )  ->  Optional[int]:
							return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )






					@slow
					def   A  (				self     :						str   )  ->  List[Any]:
							lowercase_ : List[str]							       =   TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

							lowercase_ : Optional[int]							       =   self.default_image_processor
							lowercase_ : str							       =   prepare_img()
							lowercase_ : Tuple							       =   image_processor(images=A    ,						return_tensors='''tf'''   )

							# forward pass
							lowercase_ : Union[str, Any]							       =   model(**A   )

							# verify the logits
							lowercase_ : Optional[int]							       =   tf.TensorShape((1, 10_00)   )
							self.assertEqual(outputs.logits.shape    ,						A   )

							lowercase_ : Union[str, Any]							       =   tf.constant([0.9285, 0.9015, -0.3150]   )
							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()    ,						A    ,						atol=1e-4   )   )











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



