






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







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


__lowerCAmelCase		       =							{
    '''configuration_encodec''': [
        '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''EncodecConfig''',
    ],
    '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __lowerCAmelCase		       =							[
     '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''EncodecModel''',
     '''EncodecPreTrainedModel''',
 ]

if TYPE_CHECKING:
 from .configuration_encodec import (
     ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP,
     EncodecConfig,
 )
 from .feature_extraction_encodec import EncodecFeatureExtractor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_encodec import (
      ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST,
      EncodecModel,
      EncodecPreTrainedModel,
  )

else:
 import sys

 __lowerCAmelCase		       =							_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


