


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


__UpperCamelCase     		=							logging.get_logger(__name__)


# General docstring
__UpperCamelCase     		=							'MobileNetV1Config'

# Base docstring
__UpperCamelCase     		=							'google/mobilenet_v1_1.0_224'
__UpperCamelCase     		=							[1, 1_0_2_4, 7, 7]

# Image classification docstring
__UpperCamelCase     		=							'google/mobilenet_v1_1.0_224'
__UpperCamelCase     		=							'tabby, tabby cat'


__UpperCamelCase     		=							[
    'google/mobilenet_v1_1.0_224',
    'google/mobilenet_v1_0.75_192',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]
def 							UpperCamelCase_(					_A :Optional[Any]					,  _A :str					,  _A :Optional[Any]=None	)->		str:
			UpperCamelCase__       =							{}

			if isinstance(_A					,  _A	):
						UpperCamelCase__       =							model.mobilenet_va
			else:
						UpperCamelCase__       =							model

			UpperCamelCase__       =							"MobilenetV1/Conv2d_0/"
			UpperCamelCase__       =							backbone.conv_stem.convolution.weight
			UpperCamelCase__       =							backbone.conv_stem.normalization.bias
			UpperCamelCase__       =							backbone.conv_stem.normalization.weight
			UpperCamelCase__       =							backbone.conv_stem.normalization.running_mean
			UpperCamelCase__       =							backbone.conv_stem.normalization.running_var

			for i in range(13	):
						UpperCamelCase__       =							i + 1
						UpperCamelCase__       =							i * 2

						UpperCamelCase__       =							backbone.layer[pt_index]
						UpperCamelCase__       =							F'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
						UpperCamelCase__       =							pointer.convolution.weight
						UpperCamelCase__       =							pointer.normalization.bias
						UpperCamelCase__       =							pointer.normalization.weight
						UpperCamelCase__       =							pointer.normalization.running_mean
						UpperCamelCase__       =							pointer.normalization.running_var

						UpperCamelCase__       =							backbone.layer[pt_index + 1]
						UpperCamelCase__       =							F'''MobilenetV1/Conv2d_{tf_index}_pointwise/'''
						UpperCamelCase__       =							pointer.convolution.weight
						UpperCamelCase__       =							pointer.normalization.bias
						UpperCamelCase__       =							pointer.normalization.weight
						UpperCamelCase__       =							pointer.normalization.running_mean
						UpperCamelCase__       =							pointer.normalization.running_var

			if isinstance(_A					,  _A	):
						UpperCamelCase__       =							"MobilenetV1/Logits/Conv2d_1c_1x1/"
						UpperCamelCase__       =							model.classifier.weight
						UpperCamelCase__       =							model.classifier.bias

			return tf_to_pt_map
def 							UpperCamelCase_(					_A :List[str]					,  _A :Any					,  _A :List[Any]	)->		int:
			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
			UpperCamelCase__       =							tf.train.list_variables(_A	)
			UpperCamelCase__       =							{}
			for name, shape in init_vars:
						logger.info(F'''Loading TF weight {name} with shape {shape}'''	)
						UpperCamelCase__       =							tf.train.load_variable(_A					,  _A	)
						UpperCamelCase__       =							array

			# Build TF to PyTorch weights loading map
			UpperCamelCase__       =							_build_tf_to_pytorch_map(_A					,  _A					,  _A	)

			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

						UpperCamelCase__       =							tf_weights[name]

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

						tf_weights.pop(_A					,  _A	)
						tf_weights.pop(name + "/RMSProp"					,  _A	)
						tf_weights.pop(name + "/RMSProp_1"					,  _A	)
						tf_weights.pop(name + "/ExponentialMovingAverage"					,  _A	)

			logger.info(F'''Weights not copied to PyTorch model: {', '.join(tf_weights.keys()	)}'''	)
			return model
def 							UpperCamelCase_(					_A :torch.Tensor					,  _A :nn.Convad	)->		torch.Tensor:
			UpperCamelCase__,   UpperCamelCase__       =							features.shape[-2:]
			UpperCamelCase__,   UpperCamelCase__       =							conv_layer.stride
			UpperCamelCase__,   UpperCamelCase__       =							conv_layer.kernel_size

			if in_height % stride_height == 0:
						UpperCamelCase__       =							max(kernel_height - stride_height					,  0	)
			else:
						UpperCamelCase__       =							max(kernel_height - (in_height % stride_height)					,  0	)

			if in_width % stride_width == 0:
						UpperCamelCase__       =							max(kernel_width - stride_width					,  0	)
			else:
						UpperCamelCase__       =							max(kernel_width - (in_width % stride_width)					,  0	)

			UpperCamelCase__       =							pad_along_width // 2
			UpperCamelCase__       =							pad_along_width - pad_left
			UpperCamelCase__       =							pad_along_height // 2
			UpperCamelCase__       =							pad_along_height - pad_top

			UpperCamelCase__       =							(pad_left, pad_right, pad_top, pad_bottom)
			return nn.functional.pad(_A					,  _A					,  "constant"					,  0.0	)







class 							lowerCamelCase__						(				nn.Module   ):






			"""simple docstring"""






			def __init__(				self   ,    snake_case   ,    snake_case   ,    snake_case   ,    snake_case   ,    snake_case = 1   ,    snake_case = 1   ,    snake_case = False   ,    snake_case = True   ,    snake_case = True   ,    ):

						'''simple docstring'''


						super().__init__()
						UpperCamelCase__       =							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.'''  )

						UpperCamelCase__       =							0 if config.tf_padding else int((kernel_size - 1) / 2  )

						UpperCamelCase__       =							nn.Convad(
						    in_channels=snake_case   ,    out_channels=snake_case   ,    kernel_size=snake_case   ,    stride=snake_case   ,    padding=snake_case   ,    groups=snake_case   ,    bias=snake_case   ,    padding_mode="zeros"   ,    )

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

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







			def 					snake_case__					(				self   ,    snake_case  ):

						'''simple docstring'''


						if self.config.tf_padding:
									UpperCamelCase__       =							apply_tf_padding(snake_case   ,    self.convolution  )
						UpperCamelCase__       =							self.convolution(snake_case  )
						if self.normalization is not None:
									UpperCamelCase__       =							self.normalization(snake_case  )
						if self.activation is not None:
									UpperCamelCase__       =							self.activation(snake_case  )
						return features







class 							lowerCamelCase__						(				UpperCAmelCase   ):






			"""simple docstring"""






			_UpperCamelCase		:       Tuple 			=		MobileNetVaConfig
			_UpperCamelCase		:       Union[str, Any] 			=		load_tf_weights_in_mobilenet_va
			_UpperCamelCase		:       Tuple 			=		'mobilenet_v1'
			_UpperCamelCase		:       Union[str, Any] 			=		'pixel_values'
			_UpperCamelCase		:       Any 			=		False




			def 					snake_case__					(				self   ,    snake_case  ):

						'''simple docstring'''


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



__UpperCamelCase     		=							R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

__UpperCamelCase     		=							R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`MobileNetV1ImageProcessor.__call__`] for details.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'







@add_start_docstrings(
    'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.'       ,						UpperCAmelCase       ,						)
class 							lowerCamelCase__						(				UpperCAmelCase   ):






			"""simple docstring"""






			def __init__(				self   ,    snake_case   ,    snake_case = True  ):

						'''simple docstring'''


						super().__init__(snake_case  )
						UpperCamelCase__       =							config

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

						UpperCamelCase__       =							MobileNetVaConvLayer(
						    snake_case   ,    in_channels=config.num_channels   ,    out_channels=snake_case   ,    kernel_size=3   ,    stride=2   ,    )

						UpperCamelCase__       =							[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

						UpperCamelCase__       =							nn.ModuleList()
						for i in range(13  ):
									UpperCamelCase__       =							out_channels

									if strides[i] == 2 or i == 0:
												depth *= 2
												UpperCamelCase__       =							max(int(depth * config.depth_multiplier  )   ,    config.min_depth  )

									self.layer.append(
									    MobileNetVaConvLayer(
									        snake_case   ,    in_channels=snake_case   ,    out_channels=snake_case   ,    kernel_size=3   ,    stride=strides[i]   ,    groups=snake_case   ,    )  )

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

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

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




			def 					snake_case__					(				self   ,    snake_case  ):

						'''simple docstring'''


						raise NotImplementedError







			@add_start_docstrings_to_model_forward(snake_case  )
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC   ,    output_type=snake_case   ,    config_class=_CONFIG_FOR_DOC   ,    modality="vision"   ,    expected_output=_EXPECTED_OUTPUT_SHAPE   ,    )
			def 					snake_case__					(				self   ,    snake_case = None   ,    snake_case = None   ,    snake_case = None   ,    ):

						'''simple docstring'''


						UpperCamelCase__       =							(
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						UpperCamelCase__       =							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"  )

						UpperCamelCase__       =							self.conv_stem(snake_case  )

						UpperCamelCase__       =							() if output_hidden_states else None

						for i, layer_module in enumerate(self.layer  ):
									UpperCamelCase__       =							layer_module(snake_case  )

									if output_hidden_states:
												UpperCamelCase__       =							all_hidden_states + (hidden_states,)

						UpperCamelCase__       =							hidden_states

						if self.pooler is not None:
									UpperCamelCase__       =							torch.flatten(self.pooler(snake_case  )   ,    start_dim=1  )
						else:
									UpperCamelCase__       =							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=snake_case   ,    pooler_output=snake_case   ,    hidden_states=snake_case   ,    )







@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    '       ,						UpperCAmelCase       ,						)
class 							lowerCamelCase__						(				UpperCAmelCase   ):






			"""simple docstring"""






			def __init__(				self   ,    snake_case  ):

						'''simple docstring'''


						super().__init__(snake_case  )

						UpperCamelCase__       =							config.num_labels
						UpperCamelCase__       =							MobileNetVaModel(snake_case  )

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

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

						'''simple docstring'''


						UpperCamelCase__       =							return_dict if return_dict is not None else self.config.use_return_dict

						UpperCamelCase__       =							self.mobilenet_va(snake_case   ,    output_hidden_states=snake_case   ,    return_dict=snake_case  )

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

						UpperCamelCase__       =							self.classifier(self.dropout(snake_case  )  )

						UpperCamelCase__       =							None
						if labels is not None:
									if self.config.problem_type is None:
												if self.num_labels == 1:
															UpperCamelCase__       =							"regression"
												elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
															UpperCamelCase__       =							"single_label_classification"
												else:
															UpperCamelCase__       =							"multi_label_classification"

									if self.config.problem_type == "regression":
												UpperCamelCase__       =							MSELoss()
												if self.num_labels == 1:
															UpperCamelCase__       =							loss_fct(logits.squeeze()   ,    labels.squeeze()  )
												else:
															UpperCamelCase__       =							loss_fct(snake_case   ,    snake_case  )
									elif self.config.problem_type == "single_label_classification":
												UpperCamelCase__       =							CrossEntropyLoss()
												UpperCamelCase__       =							loss_fct(logits.view(-1   ,    self.num_labels  )   ,    labels.view(-1  )  )
									elif self.config.problem_type == "multi_label_classification":
												UpperCamelCase__       =							BCEWithLogitsLoss()
												UpperCamelCase__       =							loss_fct(snake_case   ,    snake_case  )

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

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






from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
						if not (is_transformers_available() and is_torch_available()):
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline
else:
						from .pipeline_kandinsky import KandinskyPipeline
						from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
						from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
						from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
						from .text_encoder import MultilingualCLIP


