





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


__lowercase	: Tuple       =logging.get_logger(__name__)


# General docstring
__lowercase	: Dict       ="""MobileNetV1Config"""

# Base docstring
__lowercase	: Union[str, Any]       ="""google/mobilenet_v1_1.0_224"""
__lowercase	: str       =[1, 1024, 7, 7]

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


__lowercase	: Dict       =[
    """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      a__			(       lowercase__	,     lowercase__	,     lowercase__=None	):






   '''simple docstring'''






   UpperCAmelCase_           ={}

   if isinstance(lowercase__	,     lowercase__	):
      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(1_3	):
      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(lowercase__	,     lowercase__	):
      UpperCAmelCase_           ="MobilenetV1/Logits/Conv2d_1c_1x1/"
      UpperCAmelCase_           =model.classifier.weight
      UpperCAmelCase_           =model.classifier.bias

   return tf_to_pt_map




def      a__			(       lowercase__	,     lowercase__	,     lowercase__	):






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

   # Build TF to PyTorch weights loading map
   UpperCAmelCase_           =_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

      UpperCAmelCase_           =tf_weights[name]

      if "depthwise_weights" in name:
         logger.info("Transposing depthwise"	)
         UpperCAmelCase_           =np.transpose(lowercase__	,     (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(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}'	)
      UpperCAmelCase_           =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      a__			(       lowercase__	,     lowercase__	):






   '''simple docstring'''






   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(lowercase__	,     lowercase__	,     "constant"	,     0.0	)

class   A							(						nn.Module    ):



      def __init__(						self:    Optional[Any]		,	_lowerCAmelCase:    MobileNetVaConfig		,	_lowerCAmelCase:    int		,	_lowerCAmelCase:    int		,	_lowerCAmelCase:    int		,	_lowerCAmelCase:    Optional[int] = 1		,	_lowerCAmelCase:    Optional[int] = 1		,	_lowerCAmelCase:    bool = False		,	_lowerCAmelCase:    Optional[bool] = True		,	_lowerCAmelCase:    Optional[bool or str] = True		,	)    ->     None:
         '''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=_lowerCAmelCase		,	out_channels=_lowerCAmelCase		,	kernel_size=_lowerCAmelCase		,	stride=_lowerCAmelCase		,	padding=_lowerCAmelCase		,	groups=_lowerCAmelCase		,	bias=_lowerCAmelCase		,	padding_mode="zeros"		,	)

         if use_normalization:
            UpperCAmelCase_           =nn.BatchNormad(
                num_features=_lowerCAmelCase		,	eps=config.layer_norm_eps		,	momentum=0.99_97		,	affine=_lowerCAmelCase		,	track_running_stats=_lowerCAmelCase		,	)
         else:
            UpperCAmelCase_           =None

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






      def 						lowerCAmelCase__     (						self:    Union[str, Any]		,	_lowerCAmelCase:    torch.Tensor							)    ->     torch.Tensor:
         '''simple docstring'''

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

class   A							(						__lowercase    ):
      _snake_case				  =MobileNetVaConfig
      _snake_case				  =load_tf_weights_in_mobilenet_va
      _snake_case				  ='''mobilenet_v1'''
      _snake_case				  ='''pixel_values'''
      _snake_case				  =False



      def 						lowerCAmelCase__     (						self:    Optional[int]		,	_lowerCAmelCase:    Union[nn.Linear, nn.Convad]							)    ->     None:
         '''simple docstring'''

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

__lowercase	: 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.
"""

__lowercase	: List[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.'''		,   __lowercase		,   )
class   A							(						__lowercase    ):



      def __init__(						self:    str		,	_lowerCAmelCase:    MobileNetVaConfig		,	_lowerCAmelCase:    bool = True							)    ->     Any:
         '''simple docstring'''

         super().__init__(_lowerCAmelCase							)
         UpperCAmelCase_           =config

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

         UpperCAmelCase_           =MobileNetVaConvLayer(
             _lowerCAmelCase		,	in_channels=config.num_channels		,	out_channels=_lowerCAmelCase		,	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(
                    _lowerCAmelCase		,	in_channels=_lowerCAmelCase		,	out_channels=_lowerCAmelCase		,	kernel_size=3		,	stride=strides[i]		,	groups=_lowerCAmelCase		,	)							)

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

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

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



      def 						lowerCAmelCase__     (						self:    Union[str, Any]		,	_lowerCAmelCase:    str							)    ->     List[str]:
         '''simple docstring'''

         raise NotImplementedError






      @add_start_docstrings_to_model_forward(_lowerCAmelCase							)
      @add_code_sample_docstrings(
          checkpoint=_CHECKPOINT_FOR_DOC		,	output_type=_lowerCAmelCase		,	config_class=_CONFIG_FOR_DOC		,	modality="vision"		,	expected_output=_EXPECTED_OUTPUT_SHAPE		,	)
      def 						lowerCAmelCase__     (						self:    Optional[int]		,	_lowerCAmelCase:    Optional[torch.Tensor] = None		,	_lowerCAmelCase:    Optional[bool] = None		,	_lowerCAmelCase:    Optional[bool] = None		,	)    ->     Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
         '''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(_lowerCAmelCase							)

         UpperCAmelCase_           =() if output_hidden_states else None

         for i, layer_module in enumerate(self.layer							):
            UpperCAmelCase_           =layer_module(_lowerCAmelCase							)

            if output_hidden_states:
               UpperCAmelCase_           =all_hidden_states + (hidden_states,)

         UpperCAmelCase_           =hidden_states

         if self.pooler is not None:
            UpperCAmelCase_           =torch.flatten(self.pooler(_lowerCAmelCase							)		,	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=_lowerCAmelCase		,	pooler_output=_lowerCAmelCase		,	hidden_states=_lowerCAmelCase		,	)

@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.
    '''		,   __lowercase		,   )
class   A							(						__lowercase    ):



      def __init__(						self:    Dict		,	_lowerCAmelCase:    MobileNetVaConfig							)    ->     None:
         '''simple docstring'''

         super().__init__(_lowerCAmelCase							)

         UpperCAmelCase_           =config.num_labels
         UpperCAmelCase_           =MobileNetVaModel(_lowerCAmelCase							)

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

         # Classifier head
         UpperCAmelCase_           =nn.Dropout(config.classifier_dropout_prob		,	inplace=_lowerCAmelCase							)
         UpperCAmelCase_           =nn.Linear(_lowerCAmelCase		,	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(_lowerCAmelCase							)
      @add_code_sample_docstrings(
          checkpoint=_IMAGE_CLASS_CHECKPOINT		,	output_type=_lowerCAmelCase		,	config_class=_CONFIG_FOR_DOC		,	expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT		,	)
      def 						lowerCAmelCase__     (						self:    Any		,	_lowerCAmelCase:    Optional[torch.Tensor] = None		,	_lowerCAmelCase:    Optional[bool] = None		,	_lowerCAmelCase:    Optional[torch.Tensor] = None		,	_lowerCAmelCase:    Optional[bool] = None		,	)    ->     Union[tuple, ImageClassifierOutputWithNoAttention]:
         '''simple docstring'''

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

         UpperCAmelCase_           =self.mobilenet_va(_lowerCAmelCase		,	output_hidden_states=_lowerCAmelCase		,	return_dict=_lowerCAmelCase							)

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

         UpperCAmelCase_           =self.classifier(self.dropout(_lowerCAmelCase							)							)

         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(_lowerCAmelCase		,	_lowerCAmelCase							)
            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(_lowerCAmelCase		,	_lowerCAmelCase							)

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

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





import argparse
import json
from collections import OrderedDict
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
SCREAMING_SNAKE_CASE			:						int				  =		logging.get_logger(__name__)



def 	__A		(      _A				,					_A				,					_A				,					_A       ):



 """simple docstring"""


 __a							=	original_name.split("."       )[0]
 __a							=	key.split("."       )
 __a							=	int(key_list[key_list.index(_A       ) - 2]       )
 __a							=	int(key_list[key_list.index(_A       ) - 1]       )
 __a							=	orig_block_num - offset

 __a							=	key.replace(f"""{orig_block_num}.{layer_num}.{original_name}"""				,					f"""block.{new_block_num}.{layer_num}.{new_name}"""       )
 return key



def 	__A		(      _A       ):



 """simple docstring"""


 __a							=	OrderedDict()
 __a							,  __a							=	0, 0
 for key, value in state_dict.items():
  if key.startswith("network"       ):
   __a							=	key.replace("network"				,					"poolformer.encoder"       )
  if "proj" in key:
   # Works for the first embedding as well as the internal embedding layers
   if key.endswith("bias"       ) and "patch_embed" not in key:
    patch_emb_offset += 1
   __a							=	key[: key.find("proj"       )]
   __a							=	key.replace(_A				,					f"""patch_embeddings.{total_embed_found}."""       )
   __a							=	key.replace("proj"				,					"projection"       )
   if key.endswith("bias"       ):
    total_embed_found += 1
  if "patch_embeddings" in key:
   __a							=	"poolformer.encoder." + key
  if "mlp.fc1" in key:
   __a							=	replace_key_with_offset(_A				,					_A				,					"mlp.fc1"				,					"output.conv1"       )
  if "mlp.fc2" in key:
   __a							=	replace_key_with_offset(_A				,					_A				,					"mlp.fc2"				,					"output.conv2"       )
  if "norm1" in key:
   __a							=	replace_key_with_offset(_A				,					_A				,					"norm1"				,					"before_norm"       )
  if "norm2" in key:
   __a							=	replace_key_with_offset(_A				,					_A				,					"norm2"				,					"after_norm"       )
  if "layer_scale_1" in key:
   __a							=	replace_key_with_offset(_A				,					_A				,					"layer_scale_1"				,					"layer_scale_1"       )
  if "layer_scale_2" in key:
   __a							=	replace_key_with_offset(_A				,					_A				,					"layer_scale_2"				,					"layer_scale_2"       )
  if "head" in key:
   __a							=	key.replace("head"				,					"classifier"       )
  __a							=	value
 return new_state_dict



def 	__A		(      ):



 """simple docstring"""


 __a							=	"http://images.cocodataset.org/val2017/000000039769.jpg"
 __a							=	Image.open(requests.get(_A				,					stream=_A       ).raw       )

 return image



@torch.no_grad()
def 	__A		(      _A				,					_A				,					_A       ):



 """simple docstring"""


 __a							=	PoolFormerConfig()

 # set attributes based on model_name
 __a							=	"huggingface/label-files"
 __a							=	model_name[-3:]
 __a							=	1000
 __a							=	"imagenet-1k-id2label.json"
 __a							=	(1, 1000)

 # set config attributes
 __a							=	json.load(open(hf_hub_download(_A				,					_A				,					repo_type="dataset"       )				,					"r"       )       )
 __a							=	{int(_A       ): v for k, v in idalabel.items()}
 __a							=	idalabel
 __a							=	{v: k for k, v in idalabel.items()}
 if size == "s12":
  __a							=	[2, 2, 6, 2]
  __a							=	[64, 128, 320, 512]
  __a							=	4.0
  __a							=	0.9
 elif size == "s24":
  __a							=	[4, 4, 12, 4]
  __a							=	[64, 128, 320, 512]
  __a							=	4.0
  __a							=	0.9
 elif size == "s36":
  __a							=	[6, 6, 18, 6]
  __a							=	[64, 128, 320, 512]
  __a							=	4.0
  __a							=	1E-6
  __a							=	0.9
 elif size == "m36":
  __a							=	[6, 6, 18, 6]
  __a							=	[96, 192, 384, 768]
  __a							=	4.0
  __a							=	1E-6
  __a							=	0.95
 elif size == "m48":
  __a							=	[8, 8, 24, 8]
  __a							=	[96, 192, 384, 768]
  __a							=	4.0
  __a							=	1E-6
  __a							=	0.95
 else:
  raise ValueError(f"""Size {size} not supported"""       )

 # load image processor
 __a							=	PoolFormerImageProcessor(crop_pct=_A       )

 # Prepare image
 __a							=	prepare_img()
 __a							=	image_processor(images=_A				,					return_tensors="pt"       ).pixel_values

 logger.info(f"""Converting model {model_name}..."""       )

 # load original state dict
 __a							=	torch.load(_A				,					map_location=torch.device("cpu"       )       )

 # rename keys
 __a							=	rename_keys(_A       )

 # create HuggingFace model and load state dict
 __a							=	PoolFormerForImageClassification(_A       )
 model.load_state_dict(_A       )
 model.eval()

 # Define image processor
 __a							=	PoolFormerImageProcessor(crop_pct=_A       )
 __a							=	image_processor(images=prepare_img()				,					return_tensors="pt"       ).pixel_values

 # forward pass
 __a							=	model(_A       )
 __a							=	outputs.logits

 # define expected logit slices for different models
 if size == "s12":
  __a							=	torch.tensor([-0.3045, -0.6758, -0.4869]       )
 elif size == "s24":
  __a							=	torch.tensor([0.4402, -0.1374, -0.8045]       )
 elif size == "s36":
  __a							=	torch.tensor([-0.6080, -0.5133, -0.5898]       )
 elif size == "m36":
  __a							=	torch.tensor([0.3952, 0.2263, -1.2668]       )
 elif size == "m48":
  __a							=	torch.tensor([0.1167, -0.0656, -0.3423]       )
 else:
  raise ValueError(f"""Size {size} not supported"""       )

 # verify logits
 assert logits.shape == expected_shape
 assert torch.allclose(logits[0, :3]				,					_A				,					atol=1E-2       )

 # finally, save model and image processor
 logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}..."""       )
 Path(_A       ).mkdir(exist_ok=_A       )
 model.save_pretrained(_A       )
 print(f"""Saving image processor to {pytorch_dump_folder_path}"""       )
 image_processor.save_pretrained(_A       )


if __name__ == "__main__":
  SCREAMING_SNAKE_CASE			:						Union[str, Any]				  =		argparse.ArgumentParser()

  parser.add_argument(
      """--model_name""",
      default="""poolformer_s12""",
      type=str,
      help="""Name of the model you'd like to convert.""",
  )
  parser.add_argument(
      """--checkpoint_path""", default=None, type=str, help="""Path to the original PyTorch checkpoint (.pth file)."""
  )
  parser.add_argument(
      """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model."""
  )
  SCREAMING_SNAKE_CASE			:						Any				  =		parser.parse_args()
  convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)


