






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      :		Any 					=     logging.get_logger(__name__)


# General docstring
_UpperCAmelCase      :		Optional[Any] 					=     "MobileNetV1Config"

# Base docstring
_UpperCAmelCase      :		List[str] 					=     "google/mobilenet_v1_1.0_224"
_UpperCAmelCase      :		Any 					=     [1, 1_024, 7, 7]

# Image classification docstring
_UpperCAmelCase      :		List[str] 					=     "google/mobilenet_v1_1.0_224"
_UpperCAmelCase      :		str 					=     "tabby, tabby cat"


_UpperCAmelCase      :		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 						lowerCAmelCase_		(lowercase__    :							List[str]  ,       lowercase__    :							Any  ,       lowercase__    :							Optional[Any]=None							)		->     Any:


				'''simple docstring'''




				lowerCAmelCase__         =    {}

				if isinstance(lowercase__  ,       lowercase__							):
								lowerCAmelCase__         =    model.mobilenet_va
				else:
								lowerCAmelCase__         =    model

				lowerCAmelCase__         =    '''MobilenetV1/Conv2d_0/'''
				lowerCAmelCase__         =    backbone.conv_stem.convolution.weight
				lowerCAmelCase__         =    backbone.conv_stem.normalization.bias
				lowerCAmelCase__         =    backbone.conv_stem.normalization.weight
				lowerCAmelCase__         =    backbone.conv_stem.normalization.running_mean
				lowerCAmelCase__         =    backbone.conv_stem.normalization.running_var

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

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

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

				if isinstance(lowercase__  ,       lowercase__							):
								lowerCAmelCase__         =    '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
								lowerCAmelCase__         =    model.classifier.weight
								lowerCAmelCase__         =    model.classifier.bias

				return tf_to_pt_map





def 						lowerCAmelCase_		(lowercase__    :							int  ,       lowercase__    :							Tuple  ,       lowercase__    :							Any							)		->     Optional[int]:


				'''simple docstring'''




				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
				lowerCAmelCase__         =    tf.train.list_variables(lowercase__							)
				lowerCAmelCase__         =    {}
				for name, shape in init_vars:
								logger.info(f'Loading TF weight {name} with shape {shape}'							)
								lowerCAmelCase__         =    tf.train.load_variable(lowercase__  ,       lowercase__							)
								lowerCAmelCase__         =    array

				# Build TF to PyTorch weights loading map
				lowerCAmelCase__         =    _build_tf_to_pytorch_map(lowercase__  ,       lowercase__  ,       lowercase__							)

				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

								lowerCAmelCase__         =    tf_weights[name]

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

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

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





def 						lowerCAmelCase_		(lowercase__    :							torch.Tensor  ,       lowercase__    :							nn.Convad							)		->     torch.Tensor:


				'''simple docstring'''




				lowerCAmelCase__      ,		lowerCAmelCase__         =    features.shape[-2:]
				lowerCAmelCase__      ,		lowerCAmelCase__         =    conv_layer.stride
				lowerCAmelCase__      ,		lowerCAmelCase__         =    conv_layer.kernel_size

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

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

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

				lowerCAmelCase__         =    (pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(lowercase__  ,       lowercase__  ,       '''constant'''  ,       0.0							)
class 			lowerCAmelCase_							(					nn.Module       ):




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

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

											lowerCAmelCase__         =    nn.Convad(
											    in_channels=__UpperCAmelCase			,				out_channels=__UpperCAmelCase			,				kernel_size=__UpperCAmelCase			,				stride=__UpperCAmelCase			,				padding=__UpperCAmelCase			,				groups=__UpperCAmelCase			,				bias=__UpperCAmelCase			,				padding_mode='''zeros'''			,				)

											if use_normalization:
															lowerCAmelCase__         =    nn.BatchNormad(
															    num_features=__UpperCAmelCase			,				eps=config.layer_norm_eps			,				momentum=0.9_997			,				affine=__UpperCAmelCase			,				track_running_stats=__UpperCAmelCase			,				)
											else:
															lowerCAmelCase__         =    None

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




							def     __snake_case       ( self  : str			,				SCREAMING_SNAKE_CASE_  : torch.Tensor						):


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



class 			lowerCAmelCase_							(					snake_case__       ):
							UpperCamelCase_		:int		   =     MobileNetVaConfig
							UpperCamelCase_		:Tuple		   =     load_tf_weights_in_mobilenet_va
							UpperCamelCase_		:Optional[int]		   =     'mobilenet_v1'
							UpperCamelCase_		:str		   =     'pixel_values'
							UpperCamelCase_		:Union[str, Any]		   =     False




							def     __snake_case       ( self  : Optional[int]			,				SCREAMING_SNAKE_CASE_  : Union[nn.Linear, nn.Convad]						):


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



_UpperCAmelCase      :		Tuple 					=     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      :		List[Any] 					=     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.'  ,     snake_case__  ,     )
class 			lowerCAmelCase_							(					snake_case__       ):




							def __init__( self  : Tuple			,				SCREAMING_SNAKE_CASE_  : MobileNetVaConfig			,				SCREAMING_SNAKE_CASE_  : bool = True						):
											super().__init__(__UpperCAmelCase						)
											lowerCAmelCase__         =    config

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

											lowerCAmelCase__         =    MobileNetVaConvLayer(
											    __UpperCAmelCase			,				in_channels=config.num_channels			,				out_channels=__UpperCAmelCase			,				kernel_size=3			,				stride=2			,				)

											lowerCAmelCase__         =    [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

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

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

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

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

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

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




							def     __snake_case       ( self  : List[Any]			,				SCREAMING_SNAKE_CASE_  : List[str]						):
											raise NotImplementedError




							@add_start_docstrings_to_model_forward(__UpperCAmelCase						)
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC			,				output_type=__UpperCAmelCase			,				config_class=_CONFIG_FOR_DOC			,				modality='''vision'''			,				expected_output=_EXPECTED_OUTPUT_SHAPE			,				)
							def     __snake_case       ( self  : Tuple			,				SCREAMING_SNAKE_CASE_  : Optional[torch.Tensor] = None			,				SCREAMING_SNAKE_CASE_  : Optional[bool] = None			,				SCREAMING_SNAKE_CASE_  : Optional[bool] = None			,				):
											lowerCAmelCase__         =    (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											lowerCAmelCase__         =    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'''						)

											lowerCAmelCase__         =    self.conv_stem(__UpperCAmelCase						)

											lowerCAmelCase__         =    () if output_hidden_states else None

											for i, layer_module in enumerate(self.layer						):
															lowerCAmelCase__         =    layer_module(__UpperCAmelCase						)

															if output_hidden_states:
																			lowerCAmelCase__         =    all_hidden_states + (hidden_states,)

											lowerCAmelCase__         =    hidden_states

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



@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    '  ,     snake_case__  ,     )
class 			lowerCAmelCase_							(					snake_case__       ):




							def __init__( self  : Tuple			,				SCREAMING_SNAKE_CASE_  : MobileNetVaConfig						):
											super().__init__(__UpperCAmelCase						)

											lowerCAmelCase__         =    config.num_labels
											lowerCAmelCase__         =    MobileNetVaModel(__UpperCAmelCase						)

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

											# Classifier head
											lowerCAmelCase__         =    nn.Dropout(config.classifier_dropout_prob			,				inplace=__UpperCAmelCase						)
											lowerCAmelCase__         =    nn.Linear(__UpperCAmelCase			,				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(__UpperCAmelCase						)
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT			,				output_type=__UpperCAmelCase			,				config_class=_CONFIG_FOR_DOC			,				expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT			,				)
							def     __snake_case       ( self  : Dict			,				SCREAMING_SNAKE_CASE_  : Optional[torch.Tensor] = None			,				SCREAMING_SNAKE_CASE_  : Optional[bool] = None			,				SCREAMING_SNAKE_CASE_  : Optional[torch.Tensor] = None			,				SCREAMING_SNAKE_CASE_  : Optional[bool] = None			,				):
											lowerCAmelCase__         =    return_dict if return_dict is not None else self.config.use_return_dict

											lowerCAmelCase__         =    self.mobilenet_va(__UpperCAmelCase			,				output_hidden_states=__UpperCAmelCase			,				return_dict=__UpperCAmelCase						)

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

											lowerCAmelCase__         =    self.classifier(self.dropout(__UpperCAmelCase						)						)

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

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

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

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













from typing import Dict

import numpy as np
import torch

from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map
def 		_a       ( a					:Dict[str, torch.Tensor]					)				->     Dict[str, torch.Tensor]:
 a						    = []
 a						    = []
 a						    = []

 for rt in rc.restypes:
  a						    = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
  restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names]					)
  a						    = {name: i for i, name in enumerate(a					)}
  restype_atomaa_to_atomaa_list.append(
      [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types]					)

  restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names]					)

 # Add dummy mapping for restype 'UNK'
 restype_atomaa_to_atomaa_list.append([0] * 14					)
 restype_atomaa_to_atomaa_list.append([0] * 37					)
 restype_atomaa_mask_list.append([0.0] * 14					)

 a						    = torch.tensor(
     a      ,				dtype=torch.intaa      ,				device=protein['''aatype'''].device      ,				)
 a						    = torch.tensor(
     a      ,				dtype=torch.intaa      ,				device=protein['''aatype'''].device      ,				)
 a						    = torch.tensor(
     a      ,				dtype=torch.floataa      ,				device=protein['''aatype'''].device      ,				)
 a						    = protein['''aatype'''].to(torch.long					)

 # create the mapping for (residx, atom14) --> atom37, i.e. an array
 # with shape (num_res, 14) containing the atom37 indices for this protein
 a						    = restype_atomaa_to_atomaa[protein_aatype]
 a						    = restype_atomaa_mask[protein_aatype]

 a						    = residx_atomaa_mask
 a						    = residx_atomaa_to_atomaa.long()

 # create the gather indices for mapping back
 a						    = restype_atomaa_to_atomaa[protein_aatype]
 a						    = residx_atomaa_to_atomaa.long()

 # create the corresponding mask
 a						    = torch.zeros([21, 37]      ,				dtype=torch.floataa      ,				device=protein['''aatype'''].device					)
 for restype, restype_letter in enumerate(rc.restypes					):
  a						    = rc.restype_atoa[restype_letter]
  a						    = rc.residue_atoms[restype_name]
  for atom_name in atom_names:
   a						    = rc.atom_order[atom_name]
   a						    = 1

 a						    = restype_atomaa_mask[protein_aatype]
 a						    = residx_atomaa_mask

 return protein

def 		_a       ( a					:Dict[str, torch.Tensor]					)				->     Dict[str, np.ndarray]:
 a						    = tree_map(lambda a					: torch.tensor(a      ,				device=batch['''aatype'''].device					)      ,				a      ,				np.ndarray					)
 a						    = tensor_tree_map(lambda a					: np.array(a					)      ,				make_atomaa_masks(a					)					)
 return out


