





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


# General docstring
_UpperCAmelCase							:			Union[str, Any]        =							"""MobileNetV1Config"""

# Base docstring
_UpperCAmelCase							:			Dict        =							"""google/mobilenet_v1_1.0_224"""
_UpperCAmelCase							:			Union[str, Any]        =							[1, 10_24, 7, 7]

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


_UpperCAmelCase							:			Optional[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 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase=None					)     ->	List[Any]:
    lowerCamelCase__       : str   					=						{}

    if isinstance(_UpperCAmelCase		,      _UpperCAmelCase					):
        lowerCamelCase__       : List[Any]   					=						model.mobilenet_va
    else:
        lowerCamelCase__       : Any   					=						model

    lowerCamelCase__       : Union[str, Any]   					=						'MobilenetV1/Conv2d_0/'
    lowerCamelCase__       : Any   					=						backbone.conv_stem.convolution.weight
    lowerCamelCase__       : Optional[int]   					=						backbone.conv_stem.normalization.bias
    lowerCamelCase__       : List[Any]   					=						backbone.conv_stem.normalization.weight
    lowerCamelCase__       : Any   					=						backbone.conv_stem.normalization.running_mean
    lowerCamelCase__       : Optional[Any]   					=						backbone.conv_stem.normalization.running_var

    for i in range(13					):
        lowerCamelCase__       : Optional[Any]   					=						i + 1
        lowerCamelCase__       : Any   					=						i * 2

        lowerCamelCase__       : Optional[Any]   					=						backbone.layer[pt_index]
        lowerCamelCase__       : str   					=						F"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
        lowerCamelCase__       : Any   					=						pointer.convolution.weight
        lowerCamelCase__       : Any   					=						pointer.normalization.bias
        lowerCamelCase__       : Union[str, Any]   					=						pointer.normalization.weight
        lowerCamelCase__       : Dict   					=						pointer.normalization.running_mean
        lowerCamelCase__       : str   					=						pointer.normalization.running_var

        lowerCamelCase__       : Any   					=						backbone.layer[pt_index + 1]
        lowerCamelCase__       : Tuple   					=						F"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
        lowerCamelCase__       : List[Any]   					=						pointer.convolution.weight
        lowerCamelCase__       : Optional[int]   					=						pointer.normalization.bias
        lowerCamelCase__       : Union[str, Any]   					=						pointer.normalization.weight
        lowerCamelCase__       : int   					=						pointer.normalization.running_mean
        lowerCamelCase__       : Tuple   					=						pointer.normalization.running_var

    if isinstance(_UpperCAmelCase		,      _UpperCAmelCase					):
        lowerCamelCase__       : Union[str, Any]   					=						'MobilenetV1/Logits/Conv2d_1c_1x1/'
        lowerCamelCase__       : Union[str, Any]   					=						model.classifier.weight
        lowerCamelCase__       : Dict   					=						model.classifier.bias

    return tf_to_pt_map


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase					)     ->	List[str]:
    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__       : Optional[Any]   					=						tf.train.list_variables(_UpperCAmelCase					)
    lowerCamelCase__       : int   					=						{}
    for name, shape in init_vars:
        logger.info(F"""Loading TF weight {name} with shape {shape}"""					)
        lowerCamelCase__       : Optional[int]   					=						tf.train.load_variable(_UpperCAmelCase		,      _UpperCAmelCase					)
        lowerCamelCase__       : str   					=						array

    # Build TF to PyTorch weights loading map
    lowerCamelCase__       : List[str]   					=						_build_tf_to_pytorch_map(_UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase					)

    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__       : str   					=						tf_weights[name]

        if "depthwise_weights" in name:
            logger.info('Transposing depthwise'					)
            lowerCamelCase__       : Optional[int]   					=						np.transpose(_UpperCAmelCase		,      (2, 3, 0, 1)					)
        elif "weights" in name:
            logger.info('Transposing'					)
            if len(pointer.shape					) == 2:  # copying into linear layer
                lowerCamelCase__       : Any   					=						array.squeeze().transpose()
            else:
                lowerCamelCase__       : Union[str, Any]   					=						np.transpose(_UpperCAmelCase		,      (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__       : Optional[int]   					=						torch.from_numpy(_UpperCAmelCase					)

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

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


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase		,      _UpperCAmelCase					)     ->	torch.Tensor:
    lowerCamelCase__					,				lowerCamelCase__       : int   					=						features.shape[-2:]
    lowerCamelCase__					,				lowerCamelCase__       : Optional[Any]   					=						conv_layer.stride
    lowerCamelCase__					,				lowerCamelCase__       : List[Any]   					=						conv_layer.kernel_size

    if in_height % stride_height == 0:
        lowerCamelCase__       : Any   					=						max(kernel_height - stride_height		,      0					)
    else:
        lowerCamelCase__       : str   					=						max(kernel_height - (in_height % stride_height)		,      0					)

    if in_width % stride_width == 0:
        lowerCamelCase__       : Dict   					=						max(kernel_width - stride_width		,      0					)
    else:
        lowerCamelCase__       : Tuple   					=						max(kernel_width - (in_width % stride_width)		,      0					)

    lowerCamelCase__       : int   					=						pad_along_width // 2
    lowerCamelCase__       : Optional[int]   					=						pad_along_width - pad_left
    lowerCamelCase__       : Tuple   					=						pad_along_height // 2
    lowerCamelCase__       : List[str]   					=						pad_along_height - pad_top

    lowerCamelCase__       : Tuple   					=						(pad_left, pad_right, pad_top, pad_bottom)
    return nn.functional.pad(_UpperCAmelCase		,      _UpperCAmelCase		,      'constant'		,      0.0					)

class   lowerCAmelCase				(   nn.Module     ):
 def __init__( self    : int     ,	UpperCAmelCase    : MobileNetVaConfig     ,	UpperCAmelCase    : int     ,	UpperCAmelCase    : int     ,	UpperCAmelCase    : int     ,	UpperCAmelCase    : Optional[int] = 1     ,	UpperCAmelCase    : Optional[int] = 1     ,	UpperCAmelCase    : bool = False     ,	UpperCAmelCase    : Optional[bool] = True     ,	UpperCAmelCase    : Optional[bool or str] = True     ,	)     ->      None:
     super().__init__()
     lowerCamelCase__       : List[Any]   					=						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__       : int   					=						0 if config.tf_padding else int((kernel_size - 1) / 2      )

     lowerCamelCase__       : Union[str, Any]   					=						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__       : Tuple   					=						nn.BatchNormad(
             num_features=UpperCAmelCase     ,	eps=config.layer_norm_eps     ,	momentum=0.9_9_9_7     ,	affine=UpperCAmelCase     ,	track_running_stats=UpperCAmelCase     ,	)
     else:
         lowerCamelCase__       : str   					=						None

     if use_activation:
         if isinstance(UpperCAmelCase     ,	UpperCAmelCase      ):
             lowerCamelCase__       : Optional[int]   					=						ACTaFN[use_activation]
         elif isinstance(config.hidden_act     ,	UpperCAmelCase      ):
             lowerCamelCase__       : Optional[Any]   					=						ACTaFN[config.hidden_act]
         else:
             lowerCamelCase__       : List[str]   					=						config.hidden_act
     else:
         lowerCamelCase__       : Union[str, Any]   					=						None







 def 	A_      ( self    : Optional[int]     ,	UpperCAmelCase    : torch.Tensor      )     ->      torch.Tensor:
     if self.config.tf_padding:
         lowerCamelCase__       : Dict   					=						apply_tf_padding(UpperCAmelCase     ,	self.convolution      )
     lowerCamelCase__       : List[Any]   					=						self.convolution(UpperCAmelCase      )
     if self.normalization is not None:
         lowerCamelCase__       : Dict   					=						self.normalization(UpperCAmelCase      )
     if self.activation is not None:
         lowerCamelCase__       : Tuple   					=						self.activation(UpperCAmelCase      )
     return features


class   lowerCAmelCase				(   __UpperCamelCase     ):
 UpperCAmelCase__						=						MobileNetVaConfig
 UpperCAmelCase__						=						load_tf_weights_in_mobilenet_va
 UpperCAmelCase__						=						"""mobilenet_v1"""
 UpperCAmelCase__						=						"""pixel_values"""
 UpperCAmelCase__						=						False
 def 	A_      ( self    : Dict     ,	UpperCAmelCase    : Union[nn.Linear, nn.Convad]      )     ->      None:
     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							:			List[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.
"""

_UpperCAmelCase							:			Any        =							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.""",    __UpperCamelCase,    )
class   lowerCAmelCase				(   __UpperCamelCase     ):
 def __init__( self    : Optional[Any]     ,	UpperCAmelCase    : MobileNetVaConfig     ,	UpperCAmelCase    : bool = True      )     ->      Tuple:
     super().__init__(UpperCAmelCase      )
     lowerCamelCase__       : List[str]   					=						config

     lowerCamelCase__       : Optional[int]   					=						32
     lowerCamelCase__       : Dict   					=						max(int(depth * config.depth_multiplier      )     ,	config.min_depth      )

     lowerCamelCase__       : Union[str, Any]   					=						MobileNetVaConvLayer(
         UpperCAmelCase     ,	in_channels=config.num_channels     ,	out_channels=UpperCAmelCase     ,	kernel_size=3     ,	stride=2     ,	)

     lowerCamelCase__       : Tuple   					=						[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

     lowerCamelCase__       : List[str]   					=						nn.ModuleList()
     for i in range(13      ):
         lowerCamelCase__       : List[str]   					=						out_channels

         if strides[i] == 2 or i == 0:
             depth *= 2
             lowerCamelCase__       : Union[str, Any]   					=						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__       : Any   					=						nn.AdaptiveAvgPoolad((1, 1)      ) if add_pooling_layer else None

     # Initialize weights and apply final processing
     self.post_init()
 def 	A_      ( self    : Optional[Any]     ,	UpperCAmelCase    : List[str]      )     ->      Dict:
     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 	A_      ( self    : int     ,	UpperCAmelCase    : Optional[torch.Tensor] = None     ,	UpperCAmelCase    : Optional[bool] = None     ,	UpperCAmelCase    : Optional[bool] = None     ,	)     ->      Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
     lowerCamelCase__       : Optional[Any]   					=						(
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )
     lowerCamelCase__       : str   					=						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__       : Any   					=						self.conv_stem(UpperCAmelCase      )

     lowerCamelCase__       : Union[str, Any]   					=						() if output_hidden_states else None

     for i, layer_module in enumerate(self.layer      ):
         lowerCamelCase__       : List[str]   					=						layer_module(UpperCAmelCase      )

         if output_hidden_states:
             lowerCamelCase__       : str   					=						all_hidden_states + (hidden_states,)

     lowerCamelCase__       : Union[str, Any]   					=						hidden_states

     if self.pooler is not None:
         lowerCamelCase__       : List[Any]   					=						torch.flatten(self.pooler(UpperCAmelCase      )     ,	start_dim=1      )
     else:
         lowerCamelCase__       : Dict   					=						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(
    """
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """,    __UpperCamelCase,    )
class   lowerCAmelCase				(   __UpperCamelCase     ):
 def __init__( self    : str     ,	UpperCAmelCase    : MobileNetVaConfig      )     ->      None:
     super().__init__(UpperCAmelCase      )

     lowerCamelCase__       : str   					=						config.num_labels
     lowerCamelCase__       : str   					=						MobileNetVaModel(UpperCAmelCase      )

     lowerCamelCase__       : int   					=						self.mobilenet_va.layer[-1].convolution.out_channels

     # Classifier head
     lowerCamelCase__       : Any   					=						nn.Dropout(config.classifier_dropout_prob     ,	inplace=UpperCAmelCase      )
     lowerCamelCase__       : Any   					=						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 	A_      ( self    : int     ,	UpperCAmelCase    : Optional[torch.Tensor] = None     ,	UpperCAmelCase    : Optional[bool] = None     ,	UpperCAmelCase    : Optional[torch.Tensor] = None     ,	UpperCAmelCase    : Optional[bool] = None     ,	)     ->      Union[tuple, ImageClassifierOutputWithNoAttention]:
     lowerCamelCase__       : List[Any]   					=						return_dict if return_dict is not None else self.config.use_return_dict

     lowerCamelCase__       : Dict   					=						self.mobilenet_va(UpperCAmelCase     ,	output_hidden_states=UpperCAmelCase     ,	return_dict=UpperCAmelCase      )

     lowerCamelCase__       : Any   					=						outputs.pooler_output if return_dict else outputs[1]

     lowerCamelCase__       : Union[str, Any]   					=						self.classifier(self.dropout(UpperCAmelCase      )      )

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

         if self.config.problem_type == "regression":
             lowerCamelCase__       : Optional[Any]   					=						MSELoss()
             if self.num_labels == 1:
                 lowerCamelCase__       : List[Any]   					=						loss_fct(logits.squeeze()     ,	labels.squeeze()      )
             else:
                 lowerCamelCase__       : Optional[int]   					=						loss_fct(UpperCAmelCase     ,	UpperCAmelCase      )
         elif self.config.problem_type == "single_label_classification":
             lowerCamelCase__       : Tuple   					=						CrossEntropyLoss()
             lowerCamelCase__       : int   					=						loss_fct(logits.view(-1     ,	self.num_labels      )     ,	labels.view(-1      )      )
         elif self.config.problem_type == "multi_label_classification":
             lowerCamelCase__       : int   					=						BCEWithLogitsLoss()
             lowerCamelCase__       : List[str]   					=						loss_fct(UpperCAmelCase     ,	UpperCAmelCase      )

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

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












import argparse
import json
from collections import OrderedDict

import torch
from huggingface_hub import cached_download, hf_hub_url

from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase					)     ->	Dict:
    lowerCamelCase__       : Optional[int]   					=						[]
    embed.append(
        (
            F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight""",
            F"""stage{idx}.patch_embed.proj.weight""",
        )					)
    embed.append(
        (
            F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias""",
            F"""stage{idx}.patch_embed.proj.bias""",
        )					)
    embed.append(
        (
            F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight""",
            F"""stage{idx}.patch_embed.norm.weight""",
        )					)
    embed.append(
        (
            F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias""",
            F"""stage{idx}.patch_embed.norm.bias""",
        )					)
    return embed


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase		,      _UpperCAmelCase					)     ->	List[str]:
    lowerCamelCase__       : Optional[int]   					=						[]
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked""",
            F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.proj_q.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias""",
            F"""stage{idx}.blocks.{cnt}.attn.proj_q.bias""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.proj_k.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias""",
            F"""stage{idx}.blocks.{cnt}.attn.proj_k.bias""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.proj_v.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias""",
            F"""stage{idx}.blocks.{cnt}.attn.proj_v.bias""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight""",
            F"""stage{idx}.blocks.{cnt}.attn.proj.weight""",
        )					)
    attention_weights.append(
        (
            F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias""",
            F"""stage{idx}.blocks.{cnt}.attn.proj.bias""",
        )					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight""", F"""stage{idx}.blocks.{cnt}.mlp.fc1.weight""")					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias""", F"""stage{idx}.blocks.{cnt}.mlp.fc1.bias""")					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight""", F"""stage{idx}.blocks.{cnt}.mlp.fc2.weight""")					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias""", F"""stage{idx}.blocks.{cnt}.mlp.fc2.bias""")					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight""", F"""stage{idx}.blocks.{cnt}.norm1.weight""")					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias""", F"""stage{idx}.blocks.{cnt}.norm1.bias""")					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight""", F"""stage{idx}.blocks.{cnt}.norm2.weight""")					)
    attention_weights.append(
        (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias""", F"""stage{idx}.blocks.{cnt}.norm2.bias""")					)
    return attention_weights


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase					)     ->	str:
    lowerCamelCase__       : Union[str, Any]   					=						[]
    token.append((F"""cvt.encoder.stages.{idx}.cls_token""", 'stage2.cls_token')					)
    return token


def 			SCREAMING_SNAKE_CASE (			)     ->	Dict:
    lowerCamelCase__       : Tuple   					=						[]
    head.append(('layernorm.weight', 'norm.weight')					)
    head.append(('layernorm.bias', 'norm.bias')					)
    head.append(('classifier.weight', 'head.weight')					)
    head.append(('classifier.bias', 'head.bias')					)
    return head


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase					)     ->	Optional[int]:
    lowerCamelCase__       : Union[str, Any]   					=						'imagenet-1k-id2label.json'
    lowerCamelCase__       : Tuple   					=						1000

    lowerCamelCase__       : Tuple   					=						'huggingface/label-files'
    lowerCamelCase__       : Optional[int]   					=						num_labels
    lowerCamelCase__       : Optional[Any]   					=						json.load(open(cached_download(hf_hub_url(_UpperCAmelCase		,      _UpperCAmelCase		,      repo_type='dataset'					)					)		,      'r'					)					)
    lowerCamelCase__       : Optional[int]   					=						{int(_UpperCAmelCase					): v for k, v in idalabel.items()}

    lowerCamelCase__       : List[Any]   					=						idalabel
    lowerCamelCase__       : Optional[Any]   					=						{v: k for k, v in idalabel.items()}

    lowerCamelCase__       : int   					=						CvtConfig(num_labels=_UpperCAmelCase		,      idalabel=_UpperCAmelCase		,      labelaid=_UpperCAmelCase					)

    # For depth size 13 (13 = 1+2+10)
    if cvt_model.rsplit('/'		,      1					)[-1][4:6] == "13":
        lowerCamelCase__       : Dict   					=						[1, 2, 10]

    # For depth size 21 (21 = 1+4+16)
    elif cvt_model.rsplit('/'		,      1					)[-1][4:6] == "21":
        lowerCamelCase__       : List[str]   					=						[1, 4, 16]

    # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20)
    else:
        lowerCamelCase__       : Tuple   					=						[2, 2, 20]
        lowerCamelCase__       : Optional[int]   					=						[3, 12, 16]
        lowerCamelCase__       : int   					=						[192, 768, 1024]

    lowerCamelCase__       : Tuple   					=						CvtForImageClassification(_UpperCAmelCase					)
    lowerCamelCase__       : str   					=						AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k'					)
    lowerCamelCase__       : Optional[Any]   					=						image_size
    lowerCamelCase__       : int   					=						torch.load(_UpperCAmelCase		,      map_location=torch.device('cpu'					)					)

    lowerCamelCase__       : Dict   					=						OrderedDict()
    lowerCamelCase__       : Union[str, Any]   					=						[]

    for idx in range(len(config.depth					)					):
        if config.cls_token[idx]:
            lowerCamelCase__       : str   					=						list_of_state_dict + cls_token(_UpperCAmelCase					)
        lowerCamelCase__       : Tuple   					=						list_of_state_dict + embeddings(_UpperCAmelCase					)
        for cnt in range(config.depth[idx]					):
            lowerCamelCase__       : List[str]   					=						list_of_state_dict + attention(_UpperCAmelCase		,      _UpperCAmelCase					)

    lowerCamelCase__       : Optional[Any]   					=						list_of_state_dict + final()
    for gg in list_of_state_dict:
        print(_UpperCAmelCase					)
    for i in range(len(_UpperCAmelCase					)					):
        lowerCamelCase__       : List[str]   					=						original_weights[list_of_state_dict[i][1]]

    model.load_state_dict(_UpperCAmelCase					)
    model.save_pretrained(_UpperCAmelCase					)
    image_processor.save_pretrained(_UpperCAmelCase					)


# Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al

if __name__ == "__main__":
    _UpperCAmelCase							:			int        =							argparse.ArgumentParser()
    parser.add_argument(
        """--cvt_model""",
        default="""cvt-w24""",
        type=str,
        help="""Name of the cvt model you'd like to convert.""",
    )
    parser.add_argument(
        """--image_size""",
        default=3_84,
        type=int,
        help="""Input Image Size""",
    )
    parser.add_argument(
        """--cvt_file_name""",
        default=R"""cvtmodels\CvT-w24-384x384-IN-22k.pth""",
        type=str,
        help="""Input Image Size""",
    )
    parser.add_argument(
        """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
    )

    _UpperCAmelCase							:			Optional[int]        =							parser.parse_args()
    convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)





