


'''simple docstring'''
from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


UpperCAmelCase_ :     List[str]								=      logging.get_logger(__name__)

# General docstring
UpperCAmelCase_ :     str								=      'ResNetConfig'

# Base docstring
UpperCAmelCase_ :     Any								=      'microsoft/resnet-50'
UpperCAmelCase_ :     Tuple								=      [1, 2_0_4_8, 7, 7]

# Image classification docstring
UpperCAmelCase_ :     Optional[Any]								=      'microsoft/resnet-50'
UpperCAmelCase_ :     Optional[int]								=      'tiger cat'

UpperCAmelCase_ :     Tuple								=      [
    'microsoft/resnet-50',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]

class 						_lowerCamelCase					(    nn.Module				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase = 3      ,      __lowercase = 1      ,      __lowercase = "relu"						):

  """simple docstring"""







  super().__init__()
  __A  :		List[Any]       =			nn.Convad(
      UpperCAmelCase_      ,      UpperCAmelCase_      ,      kernel_size=UpperCAmelCase_      ,      stride=UpperCAmelCase_      ,      padding=kernel_size // 2      ,      bias=UpperCAmelCase_						)
  __A  :		Union[str, Any]       =			nn.BatchNormad(UpperCAmelCase_						)
  __A  :		List[Any]       =			ACTaFN[activation] if activation is not None else nn.Identity()







 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		Optional[Any]       =			self.convolution(UpperCAmelCase_						)
  __A  :		Any       =			self.normalization(UpperCAmelCase_						)
  __A  :		List[str]       =			self.activation(UpperCAmelCase_						)
  return hidden_state


class 						_lowerCamelCase					(    nn.Module				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase						):

  """simple docstring"""







  super().__init__()
  __A  :		List[Any]       =			ResNetConvLayer(
      config.num_channels      ,      config.embedding_size      ,      kernel_size=7      ,      stride=2      ,      activation=config.hidden_act						)
  __A  :		Dict       =			nn.MaxPoolad(kernel_size=3      ,      stride=2      ,      padding=1						)
  __A  :		Optional[int]       =			config.num_channels







 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		str       =			pixel_values.shape[1]
  if num_channels != self.num_channels:
   raise ValueError(
       'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'						)
  __A  :		List[str]       =			self.embedder(UpperCAmelCase_						)
  __A  :		int       =			self.pooler(UpperCAmelCase_						)
  return embedding


class 						_lowerCamelCase					(    nn.Module				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase = 2						):

  """simple docstring"""







  super().__init__()
  __A  :		Union[str, Any]       =			nn.Convad(UpperCAmelCase_      ,      UpperCAmelCase_      ,      kernel_size=1      ,      stride=UpperCAmelCase_      ,      bias=UpperCAmelCase_						)
  __A  :		Optional[int]       =			nn.BatchNormad(UpperCAmelCase_						)







 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			self.convolution(UpperCAmelCase_						)
  __A  :		int       =			self.normalization(UpperCAmelCase_						)
  return hidden_state


class 						_lowerCamelCase					(    nn.Module				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase = 1      ,      __lowercase = "relu"						):

  """simple docstring"""







  super().__init__()
  __A  :		str       =			in_channels != out_channels or stride != 1
  __A  :		int       =			(
      ResNetShortCut(UpperCAmelCase_      ,      UpperCAmelCase_      ,      stride=UpperCAmelCase_						) if should_apply_shortcut else nn.Identity()
  )
  __A  :		Any       =			nn.Sequential(
      ResNetConvLayer(UpperCAmelCase_      ,      UpperCAmelCase_      ,      stride=UpperCAmelCase_						)      ,      ResNetConvLayer(UpperCAmelCase_      ,      UpperCAmelCase_      ,      activation=UpperCAmelCase_						)      ,      )
  __A  :		Dict       =			ACTaFN[activation]







 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		List[Any]       =			hidden_state
  __A  :		List[Any]       =			self.layer(UpperCAmelCase_						)
  __A  :		List[Any]       =			self.shortcut(UpperCAmelCase_						)
  hidden_state += residual
  __A  :		int       =			self.activation(UpperCAmelCase_						)
  return hidden_state


class 						_lowerCamelCase					(    nn.Module				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase = 1      ,      __lowercase = "relu"      ,      __lowercase = 4						):

  """simple docstring"""







  super().__init__()
  __A  :		int       =			in_channels != out_channels or stride != 1
  __A  :		Any       =			out_channels // reduction
  __A  :		str       =			(
      ResNetShortCut(UpperCAmelCase_      ,      UpperCAmelCase_      ,      stride=UpperCAmelCase_						) if should_apply_shortcut else nn.Identity()
  )
  __A  :		List[Any]       =			nn.Sequential(
      ResNetConvLayer(UpperCAmelCase_      ,      UpperCAmelCase_      ,      kernel_size=1						)      ,      ResNetConvLayer(UpperCAmelCase_      ,      UpperCAmelCase_      ,      stride=UpperCAmelCase_						)      ,      ResNetConvLayer(UpperCAmelCase_      ,      UpperCAmelCase_      ,      kernel_size=1      ,      activation=UpperCAmelCase_						)      ,      )
  __A  :		Tuple       =			ACTaFN[activation]







 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		Tuple       =			hidden_state
  __A  :		int       =			self.layer(UpperCAmelCase_						)
  __A  :		Union[str, Any]       =			self.shortcut(UpperCAmelCase_						)
  hidden_state += residual
  __A  :		Any       =			self.activation(UpperCAmelCase_						)
  return hidden_state


class 						_lowerCamelCase					(    nn.Module				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase = 2      ,      __lowercase = 2      ,      ):

  """simple docstring"""







  super().__init__()

  __A  :		Any       =			ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer

  __A  :		Optional[int]       =			nn.Sequential(
      # downsampling is done in the first layer with stride of 2
      layer(UpperCAmelCase_      ,      UpperCAmelCase_      ,      stride=UpperCAmelCase_      ,      activation=config.hidden_act						)      ,      *[layer(UpperCAmelCase_      ,      UpperCAmelCase_      ,      activation=config.hidden_act						) for _ in range(depth - 1						)]      ,      )







 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		List[Any]       =			input
  for layer in self.layers:
   __A  :		Tuple       =			layer(UpperCAmelCase_						)
  return hidden_state


class 						_lowerCamelCase					(    nn.Module				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase						):

  """simple docstring"""







  super().__init__()
  __A  :		Any       =			nn.ModuleList([]						)
  # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
  self.stages.append(
      ResNetStage(
          UpperCAmelCase_      ,      config.embedding_size      ,      config.hidden_sizes[0]      ,      stride=2 if config.downsample_in_first_stage else 1      ,      depth=config.depths[0]      ,      )						)
  __A  :		List[str]       =			zip(config.hidden_sizes      ,      config.hidden_sizes[1:]						)
  for (in_channels, out_channels), depth in zip(UpperCAmelCase_      ,      config.depths[1:]						):
   self.stages.append(ResNetStage(UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_      ,      depth=UpperCAmelCase_						)						)







 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase = False      ,      __lowercase = True						):

  """simple docstring"""







  __A  :		Optional[int]       =			() if output_hidden_states else None

  for stage_module in self.stages:
   if output_hidden_states:
    __A  :		Optional[int]       =			hidden_states + (hidden_state,)

   __A  :		Dict       =			stage_module(UpperCAmelCase_						)

  if output_hidden_states:
   __A  :		List[str]       =			hidden_states + (hidden_state,)

  if not return_dict:
   return tuple(v for v in [hidden_state, hidden_states] if v is not None						)

  return BaseModelOutputWithNoAttention(
      last_hidden_state=UpperCAmelCase_      ,      hidden_states=UpperCAmelCase_      ,      )


class 						_lowerCamelCase					(    snake_case__				):




 '''simple docstring'''
 __lowercase				:		List[Any]    							=						ResNetConfig
 __lowercase				:		List[Any]    							=						"""resnet"""
 __lowercase				:		Optional[Any]    							=						"""pixel_values"""
 __lowercase				:		List[Any]    							=						True


 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(UpperCAmelCase_      ,      nn.Convad						):
   nn.init.kaiming_normal_(module.weight      ,      mode='fan_out'      ,      nonlinearity='relu'						)
  elif isinstance(UpperCAmelCase_      ,      (nn.BatchNormad, nn.GroupNorm)						):
   nn.init.constant_(module.weight      ,      1						)
   nn.init.constant_(module.bias      ,      0						)







 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase=False						):

  """simple docstring"""







  if isinstance(UpperCAmelCase_      ,      UpperCAmelCase_						):
   __A  :		List[str]       =			value


UpperCAmelCase_ :     int								=      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 ([`ResNetConfig`]): 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            [`ConvNextImageProcessor.__call__`] for details.\n\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 ResNet model outputting raw features without any specific head on top.'''    ,		snake_case__    ,		)
class 						_lowerCamelCase					(    snake_case__				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase						):

  """simple docstring"""







  super().__init__(UpperCAmelCase_						)
  __A  :		List[Any]       =			config
  __A  :		Dict       =			ResNetEmbeddings(UpperCAmelCase_						)
  __A  :		Optional[Any]       =			ResNetEncoder(UpperCAmelCase_						)
  __A  :		Any       =			nn.AdaptiveAvgPoolad((1, 1)						)
  # Initialize weights and apply final processing
  self.post_init()







 @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      ,      __lowercase      ,      __lowercase = None      ,      __lowercase = None						):

  """simple docstring"""







  __A  :		Dict       =			(
      output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  )
  __A  :		Union[str, Any]       =			return_dict if return_dict is not None else self.config.use_return_dict

  __A  :		List[str]       =			self.embedder(UpperCAmelCase_						)

  __A  :		str       =			self.encoder(
      UpperCAmelCase_      ,      output_hidden_states=UpperCAmelCase_      ,      return_dict=UpperCAmelCase_						)

  __A  :		str       =			encoder_outputs[0]

  __A  :		List[str]       =			self.pooler(UpperCAmelCase_						)

  if not return_dict:
   return (last_hidden_state, pooled_output) + encoder_outputs[1:]

  return BaseModelOutputWithPoolingAndNoAttention(
      last_hidden_state=UpperCAmelCase_      ,      pooler_output=UpperCAmelCase_      ,      hidden_states=encoder_outputs.hidden_states      ,      )


@add_start_docstrings(
    '''
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''    ,		snake_case__    ,		)
class 						_lowerCamelCase					(    snake_case__				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase						):

  """simple docstring"""







  super().__init__(UpperCAmelCase_						)
  __A  :		Any       =			config.num_labels
  __A  :		int       =			ResNetModel(UpperCAmelCase_						)
  # classification head
  __A  :		int       =			nn.Sequential(
      nn.Flatten()      ,      nn.Linear(config.hidden_sizes[-1]      ,      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      ,      __lowercase = None      ,      __lowercase = None      ,      __lowercase = None      ,      __lowercase = None      ,      ):

  """simple docstring"""







  __A  :		Optional[int]       =			return_dict if return_dict is not None else self.config.use_return_dict

  __A  :		int       =			self.resnet(UpperCAmelCase_      ,      output_hidden_states=UpperCAmelCase_      ,      return_dict=UpperCAmelCase_						)

  __A  :		int       =			outputs.pooler_output if return_dict else outputs[1]

  __A  :		Tuple       =			self.classifier(UpperCAmelCase_						)

  __A  :		Tuple       =			None

  if labels is not None:
   if self.config.problem_type is None:
    if self.num_labels == 1:
     __A  :		List[str]       =			'regression'
    elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
     __A  :		Optional[Any]       =			'single_label_classification'
    else:
     __A  :		Tuple       =			'multi_label_classification'
   if self.config.problem_type == "regression":
    __A  :		Optional[Any]       =			MSELoss()
    if self.num_labels == 1:
     __A  :		List[Any]       =			loss_fct(logits.squeeze()      ,      labels.squeeze()						)
    else:
     __A  :		Optional[int]       =			loss_fct(UpperCAmelCase_      ,      UpperCAmelCase_						)
   elif self.config.problem_type == "single_label_classification":
    __A  :		Tuple       =			CrossEntropyLoss()
    __A  :		Dict       =			loss_fct(logits.view(-1      ,      self.num_labels						)      ,      labels.view(-1						)						)
   elif self.config.problem_type == "multi_label_classification":
    __A  :		Union[str, Any]       =			BCEWithLogitsLoss()
    __A  :		List[Any]       =			loss_fct(UpperCAmelCase_      ,      UpperCAmelCase_						)

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

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


@add_start_docstrings(
    '''
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    '''    ,		snake_case__    ,		)
class 						_lowerCamelCase					(    snake_case__    ,		snake_case__				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase						):

  """simple docstring"""







  super().__init__(UpperCAmelCase_						)
  super()._init_backbone(UpperCAmelCase_						)

  __A  :		Optional[int]       =			[config.embedding_size] + config.hidden_sizes
  __A  :		int       =			ResNetEmbeddings(UpperCAmelCase_						)
  __A  :		Any       =			ResNetEncoder(UpperCAmelCase_						)

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







 @add_start_docstrings_to_model_forward(UpperCAmelCase_						)
 @replace_return_docstrings(output_type=UpperCAmelCase_      ,      config_class=_CONFIG_FOR_DOC						)
 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase = None      ,      __lowercase = None						):

  """simple docstring"""







  __A  :		Tuple       =			return_dict if return_dict is not None else self.config.use_return_dict
  __A  :		int       =			(
      output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  )

  __A  :		List[str]       =			self.embedder(UpperCAmelCase_						)

  __A  :		str       =			self.encoder(UpperCAmelCase_      ,      output_hidden_states=UpperCAmelCase_      ,      return_dict=UpperCAmelCase_						)

  __A  :		List[Any]       =			outputs.hidden_states

  __A  :		List[Any]       =			()
  for idx, stage in enumerate(self.stage_names						):
   if stage in self.out_features:
    feature_maps += (hidden_states[idx],)

  if not return_dict:
   __A  :		Dict       =			(feature_maps,)
   if output_hidden_states:
    output += (outputs.hidden_states,)
   return output

  return BackboneOutput(
      feature_maps=UpperCAmelCase_      ,      hidden_states=outputs.hidden_states if output_hidden_states else None      ,      attentions=UpperCAmelCase_      ,      )










'''simple docstring'''
import argparse
import json
from pathlib import Path

import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform

from transformers import (
    BitConfig,
    ViTHybridConfig,
    ViTHybridForImageClassification,
    ViTHybridImageProcessor,
    ViTHybridModel,
)
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
UpperCAmelCase_ :     Tuple								=      logging.get_logger(__name__)


def 			_lowercase       (				UpperCamelCase__       :					Optional[Any],				UpperCamelCase__       :					Tuple=False			):
 __A  :		List[str]       =			[]

 # fmt: off
 # stem:
 rename_keys.append(('cls_token', 'vit.embeddings.cls_token')			)
 rename_keys.append(('pos_embed', 'vit.embeddings.position_embeddings')			)

 rename_keys.append(('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight')			)
 rename_keys.append(('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias')			)

 # backbone
 rename_keys.append(('patch_embed.backbone.stem.conv.weight', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight')			)
 rename_keys.append(('patch_embed.backbone.stem.norm.weight', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight')			)
 rename_keys.append(('patch_embed.backbone.stem.norm.bias', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias')			)

 for stage_idx in range(len(config.backbone_config.depths			)			):
  for layer_idx in range(config.backbone_config.depths[stage_idx]			):
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight""")			)
   rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias""")			)

  rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight""")			)
  rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight""")			)
  rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias""")			)

 # transformer encoder
 for i in range(config.num_hidden_layers			):
  # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
  rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""")			)
  rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""")			)
  rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""")			)
  rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""")			)
  rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""")			)
  rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""")			)
  rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""")			)
  rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""")			)
  rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""")			)
  rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""")			)

 if base_model:
  # layernorm + pooler
  rename_keys.extend(
      [
          ('norm.weight', 'layernorm.weight'),
          ('norm.bias', 'layernorm.bias'),
          ('pre_logits.fc.weight', 'pooler.dense.weight'),
          ('pre_logits.fc.bias', 'pooler.dense.bias'),
      ]			)

  # if just the base model, we should remove "vit" from all keys that start with "vit"
  __A  :		List[str]       =			[(pair[0], pair[1][4:]) if pair[1].startswith('vit'			) else pair for pair in rename_keys]
 else:
  # layernorm + classification head
  rename_keys.extend(
      [
          ('norm.weight', 'vit.layernorm.weight'),
          ('norm.bias', 'vit.layernorm.bias'),
          ('head.weight', 'classifier.weight'),
          ('head.bias', 'classifier.bias'),
      ]			)
 # fmt: on

 return rename_keys


def 			_lowercase       (				UpperCamelCase__       :					Any,				UpperCamelCase__       :					int,				UpperCamelCase__       :					List[Any]=False			):
 for i in range(config.num_hidden_layers			):
  if base_model:
   __A  :		Optional[Any]       =			''
  else:
   __A  :		int       =			'vit.'
  # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
  __A  :		str       =			state_dict.pop(f"""blocks.{i}.attn.qkv.weight"""			)
  __A  :		str       =			state_dict.pop(f"""blocks.{i}.attn.qkv.bias"""			)
  # next, add query, keys and values (in that order) to the state dict
  __A  :		List[Any]       =			in_proj_weight[
      : config.hidden_size, :
  ]
  __A  :		List[Any]       =			in_proj_bias[: config.hidden_size]
  __A  :		Optional[int]       =			in_proj_weight[
      config.hidden_size : config.hidden_size * 2, :
  ]
  __A  :		int       =			in_proj_bias[
      config.hidden_size : config.hidden_size * 2
  ]
  __A  :		Dict       =			in_proj_weight[
      -config.hidden_size :, :
  ]
  __A  :		Optional[Any]       =			in_proj_bias[-config.hidden_size :]


def 			_lowercase       (				UpperCamelCase__       :					Optional[Any]			):
 __A  :		Any       =			['head.weight', 'head.bias']
 for k in ignore_keys:
  state_dict.pop(UpperCamelCase__,				UpperCamelCase__			)


def 			_lowercase       (				UpperCamelCase__       :					Any,				UpperCamelCase__       :					Any,				UpperCamelCase__       :					Union[str, Any]			):
 __A  :		Dict       =			dct.pop(UpperCamelCase__			)
 __A  :		Optional[Any]       =			val


def 			_lowercase       (				):
 __A  :		Tuple       =			'http://images.cocodataset.org/val2017/000000039769.jpg'
 __A  :		Optional[Any]       =			Image.open(requests.get(UpperCamelCase__,				stream=UpperCamelCase__			).raw			)
 return im


@torch.no_grad()
def 			_lowercase       (				UpperCamelCase__       :					Tuple,				UpperCamelCase__       :					int,				UpperCamelCase__       :					Any=False			):
 __A  :		Optional[Any]       =			BitConfig(
     global_padding='same',				layer_type='bottleneck',				depths=(3, 4, 9),				out_features=['stage3'],				embedding_dynamic_padding=UpperCamelCase__,				)
 __A  :		str       =			ViTHybridConfig(backbone_config=UpperCamelCase__,				image_size=384,				num_labels=1000			)
 __A  :		Union[str, Any]       =			False

 # load original model from timm
 __A  :		List[Any]       =			timm.create_model(UpperCamelCase__,				pretrained=UpperCamelCase__			)
 timm_model.eval()

 # load state_dict of original model, remove and rename some keys
 __A  :		Optional[int]       =			timm_model.state_dict()
 if base_model:
  remove_classification_head_(UpperCamelCase__			)
 __A  :		List[str]       =			create_rename_keys(UpperCamelCase__,				UpperCamelCase__			)
 for src, dest in rename_keys:
  rename_key(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)
 read_in_q_k_v(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)

 __A  :		List[str]       =			'huggingface/label-files'
 __A  :		Optional[Any]       =			'imagenet-1k-id2label.json'
 __A  :		Optional[int]       =			json.load(open(hf_hub_download(UpperCamelCase__,				UpperCamelCase__,				repo_type='dataset'			),				'r'			)			)
 __A  :		Optional[int]       =			{int(UpperCamelCase__			): v for k, v in idalabel.items()}
 __A  :		List[Any]       =			idalabel
 __A  :		Tuple       =			{v: k for k, v in idalabel.items()}

 # load HuggingFace model
 if vit_name[-5:] == "in21k":
  __A  :		List[Any]       =			ViTHybridModel(UpperCamelCase__			).eval()
 else:
  __A  :		int       =			ViTHybridForImageClassification(UpperCamelCase__			).eval()
 model.load_state_dict(UpperCamelCase__			)

 # create image processor
 __A  :		Tuple       =			create_transform(**resolve_data_config({},				model=UpperCamelCase__			)			)
 __A  :		Union[str, Any]       =			transform.transforms

 __A  :		str       =			{
     'bilinear': PILImageResampling.BILINEAR,
     'bicubic': PILImageResampling.BICUBIC,
     'nearest': PILImageResampling.NEAREST,
 }

 __A  :		List[str]       =			ViTHybridImageProcessor(
     do_resize=UpperCamelCase__,				size={'shortest_edge': timm_transforms[0].size},				resample=pillow_resamplings[timm_transforms[0].interpolation.value],				do_center_crop=UpperCamelCase__,				crop_size={'height': timm_transforms[1].size[0], 'width': timm_transforms[1].size[1]},				do_normalize=UpperCamelCase__,				image_mean=timm_transforms[-1].mean.tolist(),				image_std=timm_transforms[-1].std.tolist(),				)

 __A  :		Optional[Any]       =			prepare_img()
 __A  :		Any       =			transform(UpperCamelCase__			).unsqueeze(0			)
 __A  :		Dict       =			processor(UpperCamelCase__,				return_tensors='pt'			).pixel_values

 # verify pixel values
 assert torch.allclose(UpperCamelCase__,				UpperCamelCase__			)

 # verify logits
 with torch.no_grad():
  __A  :		Union[str, Any]       =			model(UpperCamelCase__			)
  __A  :		Dict       =			outputs.logits

 print('Predicted class:',				logits.argmax(-1			).item()			)
 if base_model:
  __A  :		Tuple       =			timm_model.forward_features(UpperCamelCase__			)
  assert timm_pooled_output.shape == outputs.pooler_output.shape
  assert torch.allclose(UpperCamelCase__,				outputs.pooler_output,				atol=1E-3			)
 else:
  __A  :		Any       =			timm_model(UpperCamelCase__			)
  assert timm_logits.shape == outputs.logits.shape
  assert torch.allclose(UpperCamelCase__,				outputs.logits,				atol=1E-3			)
 print('Looks ok!'			)

 if pytorch_dump_folder_path is not None:
  Path(UpperCamelCase__			).mkdir(exist_ok=UpperCamelCase__			)
  print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}"""			)
  model.save_pretrained(UpperCamelCase__			)
  print(f"""Saving processor to {pytorch_dump_folder_path}"""			)
  processor.save_pretrained(UpperCamelCase__			)

 if push_to_hub:
  print(f"""Pushing model and processor to the hub {vit_name}"""			)
  model.push_to_hub(f"""ybelkada/{vit_name}"""			)
  processor.push_to_hub(f"""ybelkada/{vit_name}"""			)


if __name__ == "__main__":
 UpperCAmelCase_ :     Optional[Any]								=      argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '--vit_name',
     default='vit_base_r50_s16_384',
     type=str,
     help='Name of the hybrid ViT timm model you\'d like to convert.',
 )
 parser.add_argument(
     '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
 )
 parser.add_argument(
     '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.'
 )

 UpperCAmelCase_ :     Union[str, Any]								=      parser.parse_args()
 convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)






