

'''simple docstring'''




# Copyright (c) 2021-, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

####################################################################################################

#
# Note: If when running this conversion script you're getting an exception:
#     ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#

import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig


def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   Tuple       ,   SCREAMING_SNAKE_CASE      :   List[str]       ,   SCREAMING_SNAKE_CASE      :   Optional[Any]=0						):
  # Format the message.
  if name is None:
    UpperCAmelCase													=	None
  else:
    UpperCAmelCase													=	'.' * max(0       ,   spaces - 2						) + '# {:' + str(50 - spaces						) + 's}'
    UpperCAmelCase													=	fmt.format(SCREAMING_SNAKE_CASE						)

  # Print and recurse (if needed).
  if isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						):
    if msg is not None:
      print(SCREAMING_SNAKE_CASE						)
    for k in val.keys():
      recursive_print(SCREAMING_SNAKE_CASE       ,   val[k]       ,   spaces + 2						)
  elif isinstance(SCREAMING_SNAKE_CASE       ,   torch.Tensor						):
    print(SCREAMING_SNAKE_CASE       ,   ':'       ,   val.size()						)
  else:
    print(SCREAMING_SNAKE_CASE       ,   ':'       ,   SCREAMING_SNAKE_CASE						)


def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   int       ,   SCREAMING_SNAKE_CASE      :   List[Any]       ,   SCREAMING_SNAKE_CASE      :   Optional[Any]       ,   SCREAMING_SNAKE_CASE      :   Any       ,   SCREAMING_SNAKE_CASE      :   str						):
  # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :]
  # for compatibility with later versions of NVIDIA Megatron-LM.
  # The inverse operation is performed inside Megatron-LM to read checkpoints:
  # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209
  # If param is the weight tensor of the self-attention block, the returned tensor
  # will have to be transposed one more time to be read by HuggingFace BERT.
  UpperCAmelCase													=	param.size()
  if checkpoint_version == 1.0:
    # version 1.0 stores [num_heads * hidden_size * num_splits, :]
    UpperCAmelCase													=	(num_heads, hidden_size, num_splits) + input_shape[1:]
    UpperCAmelCase													=	param.view(*SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	param.transpose(0       ,   2						)
    UpperCAmelCase													=	param.transpose(1       ,   2						).contiguous()
  elif checkpoint_version >= 2.0:
    # other versions store [num_heads * num_splits * hidden_size, :]
    UpperCAmelCase													=	(num_heads, num_splits, hidden_size) + input_shape[1:]
    UpperCAmelCase													=	param.view(*SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	param.transpose(0       ,   1						).contiguous()
  UpperCAmelCase													=	param.view(*SCREAMING_SNAKE_CASE						)
  return param


def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   str       ,   SCREAMING_SNAKE_CASE      :   int       ,   SCREAMING_SNAKE_CASE      :   int						):
  # The converted output model.
  UpperCAmelCase													=	{}

  # old versions did not store training args
  UpperCAmelCase													=	input_state_dict.get('args'       ,   SCREAMING_SNAKE_CASE						)
  if ds_args is not None:
    # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
    # from pprint import pprint
    # pprint(vars(ds_args))

    UpperCAmelCase													=	ds_args.tokenizer_type
    UpperCAmelCase													=	ds_args.padded_vocab_size
    UpperCAmelCase													=	ds_args.max_position_embeddings
    UpperCAmelCase													=	ds_args.hidden_size
    UpperCAmelCase													=	ds_args.num_layers
    UpperCAmelCase													=	ds_args.num_attention_heads
    UpperCAmelCase													=	ds_args.ffn_hidden_size if 'ffn_hidden_size' in ds_args else 4 * ds_args.hidden_size
    # pprint(config)

  # The number of heads.
  UpperCAmelCase													=	config.num_attention_heads
  # The hidden_size per head.
  UpperCAmelCase													=	config.hidden_size // heads
  # Megatron-LM checkpoint version
  if "checkpoint_version" in input_state_dict.keys():
    UpperCAmelCase													=	input_state_dict['checkpoint_version']
  else:
    UpperCAmelCase													=	0.0

  # The model.
  UpperCAmelCase													=	input_state_dict['model']
  # The language model.
  UpperCAmelCase													=	model['language_model']
  # The embeddings.
  UpperCAmelCase													=	lm['embedding']

  # The word embeddings.
  UpperCAmelCase													=	embeddings['word_embeddings']['weight']
  # Truncate the embedding table to vocab_size rows.
  UpperCAmelCase													=	word_embeddings[: config.vocab_size, :]
  # Store the word embeddings.
  UpperCAmelCase													=	word_embeddings

  # The position embeddings.
  UpperCAmelCase													=	embeddings['position_embeddings']['weight']
  assert pos_embeddings.size(0						) == config.max_position_embeddings and pos_embeddings.size(1						) == config.hidden_size
  # Store the position embeddings.
  UpperCAmelCase													=	pos_embeddings

  # The token-type embeddings.
  UpperCAmelCase													=	embeddings['tokentype_embeddings']['weight']
  # Store the position embeddings.
  UpperCAmelCase													=	tokentype_embeddings

  # The transformer.
  UpperCAmelCase													=	lm['transformer'] if 'transformer' in lm.keys() else lm['encoder']

  # The regex to extract layer names.
  UpperCAmelCase													=	re.compile(R'layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)'						)

  # The simple map of names for "automated" rules.
  UpperCAmelCase													=	{
      'attention.dense': '.attention.output.dense.',
      'self_attention.dense': '.attention.output.dense.',
      'mlp.dense_h_to_4h': '.intermediate.dense.',
      'mlp.dense_4h_to_h': '.output.dense.',
  }

  # Keep track of the attention/query/value tensor.
  UpperCAmelCase													=	None

  # Extract the layers.
  for key, val in transformer.items():
    # Match the name.
    UpperCAmelCase													=	layer_re.match(SCREAMING_SNAKE_CASE						)

    # Stop if that's not a layer
    if m is None:
      break

    # The index of the layer.
    UpperCAmelCase													=	int(m.group(1						)						)
    # The name of the operation.
    UpperCAmelCase													=	m.group(2						)
    # Is it a weight or a bias?
    UpperCAmelCase													=	m.group(3						)

    # The name of the layer.
    UpperCAmelCase													=	f'''bert.encoder.layer.{layer_idx}'''

    # For layernorm(s), simply store the layer norm.
    if op_name.endswith('layernorm'						):
      UpperCAmelCase													=	'attention.ln' if op_name.startswith('input'						) else 'ln'
      UpperCAmelCase													=	val

    # Transpose the QKV matrix.
    elif (
        op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
    ) and weight_or_bias == "weight":
      # Make sure the QKV pointer is nil.
      assert attention_qkv_weight is None, ""

      UpperCAmelCase													=	fix_query_key_value_ordering(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   3       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)
      # Store the tensor as we need the bias as well to interleave QKV and biases.
      UpperCAmelCase													=	out_val

    # Transpose the bias.
    elif (
        op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
    ) and weight_or_bias == "bias":
      # Make sure we read the weight tensor.
      assert attention_qkv_weight is not None, ""

      # Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
      UpperCAmelCase													=	attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
      UpperCAmelCase													=	attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
      UpperCAmelCase													=	attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

      UpperCAmelCase													=	fix_query_key_value_ordering(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   3       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)
      # Split the bias.
      UpperCAmelCase													=	out_val[0 * config.hidden_size : 1 * config.hidden_size]
      UpperCAmelCase													=	out_val[1 * config.hidden_size : 2 * config.hidden_size]
      UpperCAmelCase													=	out_val[2 * config.hidden_size : 3 * config.hidden_size]

      # Store.
      UpperCAmelCase													=	q
      UpperCAmelCase													=	q_bias
      UpperCAmelCase													=	k
      UpperCAmelCase													=	k_bias
      UpperCAmelCase													=	v
      UpperCAmelCase													=	v_bias

      # Clear the stored tensor.
      UpperCAmelCase													=	None

    # Copy weights and biases as is.
    elif weight_or_bias in ["weight", "bias"]:
      UpperCAmelCase													=	megatron_to_transformers[op_name]
      UpperCAmelCase													=	val

    # The final layernorm.
  UpperCAmelCase													=	transformer['final_layernorm.weight']
  UpperCAmelCase													=	transformer['final_layernorm.bias']

  # The pooler.
  UpperCAmelCase													=	lm['pooler']

  # Store the matrix and the bias.
  UpperCAmelCase													=	pooler['dense.weight']
  UpperCAmelCase													=	pooler['dense.bias']

  # The LM head from Megatron (for RACE).
  UpperCAmelCase													=	model['lm_head']

  # The transform matrix.
  UpperCAmelCase													=	lm_head['dense.weight']
  UpperCAmelCase													=	lm_head['dense.bias']

  # The transform LN.
  UpperCAmelCase													=	lm_head['layernorm.weight']
  UpperCAmelCase													=	lm_head['layernorm.bias']

  # For the decoder, we replicate the weights.
  UpperCAmelCase													=	word_embeddings
  UpperCAmelCase													=	lm_head['bias']

  # The classifier from Megatron (for MLNI).
  UpperCAmelCase													=	model['binary_head']

  # Store the classifier.
  UpperCAmelCase													=	binary_head['weight']
  UpperCAmelCase													=	binary_head['bias']

  # It should be done!
  return output_state_dict


def       lowerCamelCase__		(						):
  # Create the argument parser.
  UpperCAmelCase													=	argparse.ArgumentParser()
  parser.add_argument('--print-checkpoint-structure'       ,   action='store_true'						)
  parser.add_argument('path_to_checkpoint'       ,   type=SCREAMING_SNAKE_CASE       ,   help='Path to the ZIP file containing the checkpoint'						)
  parser.add_argument(
      '--config_file'       ,   default=''       ,   type=SCREAMING_SNAKE_CASE       ,   help='An optional config json file describing the pre-trained model.'       ,   )
  UpperCAmelCase													=	parser.parse_args()

  # Extract the basename.
  UpperCAmelCase													=	os.path.dirname(args.path_to_checkpoint						)

  # Load the model.
  # the .zip is very optional, let's keep it for backward compatibility
  print(f'''Extracting PyTorch state dictionary from "{args.path_to_checkpoint}"'''						)
  if args.path_to_checkpoint.endswith('.zip'						):
    with zipfile.ZipFile(args.path_to_checkpoint       ,   'r'						) as checkpoint:
      with checkpoint.open('release/mp_rank_00/model_optim_rng.pt'						) as pytorch_dict:
        UpperCAmelCase													=	torch.load(SCREAMING_SNAKE_CASE       ,   map_location='cpu'						)
  else:
    UpperCAmelCase													=	torch.load(args.path_to_checkpoint       ,   map_location='cpu'						)

  if args.config_file == "":
    # Default config of megatron-bert 345m
    UpperCAmelCase													=	MegatronBertConfig()

    # different megatron-bert-*-345m models have different vocab sizes, so override the default
    # config (which is for megatron-bert-cased-345m) with the actual vocab dimension
    UpperCAmelCase													=	input_state_dict['model']['lm_head']['bias'].numel()
  else:
    UpperCAmelCase													=	MegatronBertConfig.from_json_file(args.config_file						)

  # Convert.
  print('Converting'						)
  UpperCAmelCase													=	convert_megatron_checkpoint(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)

  # Print the structure of converted state dict.
  if args.print_checkpoint_structure:
    recursive_print(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)

  # Store the config to file.
  print('Saving config'						)
  config.save_pretrained(SCREAMING_SNAKE_CASE						)

  # Store the state_dict to file.
  UpperCAmelCase													=	os.path.join(SCREAMING_SNAKE_CASE       ,   'pytorch_model.bin'						)
  print(f'''Saving checkpoint to "{output_checkpoint_file}"'''						)
  torch.save(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)


####################################################################################################

if __name__ == "__main__":
  main()

####################################################################################################





'''simple docstring'''




import argparse
import json
import os
import re
from collections import OrderedDict
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from pprint import pprint
from typing import Dict, List, Tuple

import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs

from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import logging


logging.set_verbosity_info()
_a				: Optional[int] 							=						logging.get_logger()



@dataclass
class        lowercase_	:

  '''simple docstring'''





  __lowerCAmelCase					: nn.Module
  __lowerCAmelCase					: List[nn.Module]      =   field(default_factory=a )
  __lowerCAmelCase					: list      =   field(default_factory=a )
  __lowerCAmelCase					: Dict[str, nn.Module]      =   field(default_factory=a )
  def 						snake_case_			(     self   , a_   , a_   , a_   , a_     )							->				Optional[int]:


    """simple docstring"""
    UpperCAmelCase													=	len(list(m.modules()     )     ) == 1 or isinstance(a_   , nn.Convad     ) or isinstance(a_   , nn.BatchNormad     )
    if has_not_submodules:
      self.traced.append(a_     )
      UpperCAmelCase													=	m
  def __call__(     self   , a_     )							->				List[Any]:


    """simple docstring"""
    for name, m in self.module.named_modules():
      self.handles.append(m.register_forward_hook(partial(self._forward_hook   , name=a_     )     )     )
    self.module(a_     )
    [x.remove() for x in self.handles]
    return self





  @property
  def 						snake_case_			(     self     )							->				Union[str, Any]:


    """simple docstring"""
    # check the len of the state_dict keys to see if we have learnable params
    return {k: v for k, v in self.nameamodule.items() if len(list(v.state_dict().keys()     )     ) > 0}




class        lowercase_	(		nn.Module ):

  '''simple docstring'''





  def __init__(     self   , a_     )							->				Tuple:


    """simple docstring"""
    super().__init__()

    UpperCAmelCase													=	[]
    # - get the stem
    feature_blocks.append(('conv1', model.stem)     )
    # - get all the feature blocks
    for k, v in model.trunk_output.named_children():
      assert k.startswith('block'     ), F'''Unexpected layer name {k}'''
      UpperCAmelCase													=	len(a_     ) + 1
      feature_blocks.append((F'''res{block_index}''', v)     )

    UpperCAmelCase													=	nn.ModuleDict(a_     )





  def 						snake_case_			(     self   , a_     )							->				Optional[Any]:


    """simple docstring"""
    return get_trunk_forward_outputs(
        a_   , out_feat_keys=a_   , feature_blocks=self._feature_blocks   , )




class        lowercase_	(		a ):

  '''simple docstring'''





  def 						snake_case_			(     self     )							->				Optional[int]:


    """simple docstring"""
    return [(8, 2, 2, 8, 1.0), (8, 2, 7, 8, 1.0), (8, 2, 1_7, 8, 1.0), (8, 2, 1, 8, 1.0)]




def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   str						):
  UpperCAmelCase													=	RegNetConfig(depths=[2, 7, 17, 1]       ,   hidden_sizes=[8, 8, 8, 8]       ,   groups_width=8						)
  if "in1k" in model_name:
    UpperCAmelCase													=	RegNetForImageClassification(SCREAMING_SNAKE_CASE						)
  else:
    UpperCAmelCase													=	RegNetModel(SCREAMING_SNAKE_CASE						)
  # create from model (with small weights)
  UpperCAmelCase													=	FakeRegNetVisslWrapper(
      RegNet(FakeRegNetParams(depth=27       ,   group_width=1010       ,   w_a=1744       ,   w_a=620.83       ,   w_m=2.52						)						)						)

  with torch.no_grad():
    UpperCAmelCase													=	from_model.eval()
    UpperCAmelCase													=	our_model.eval()

    UpperCAmelCase													=	torch.randn((1, 3, 32, 32)						)
    # trace both
    UpperCAmelCase													=	Tracker(SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	dest_tracker(SCREAMING_SNAKE_CASE						).parametrized

    pprint(dest_tracker.nameamodule						)
    UpperCAmelCase													=	Tracker(SCREAMING_SNAKE_CASE						)
    UpperCAmelCase													=	src_tracker(SCREAMING_SNAKE_CASE						).parametrized

  # convert the keys -> module dict to keys -> params
  def to_params_dict(SCREAMING_SNAKE_CASE      :   Tuple						):
    UpperCAmelCase													=	OrderedDict()
    for name, module in dict_with_modules.items():
      for param_name, param in module.state_dict().items():
        UpperCAmelCase													=	param
    return params_dict

  UpperCAmelCase													=	{}

  UpperCAmelCase													=	to_params_dict(SCREAMING_SNAKE_CASE						)
  UpperCAmelCase													=	to_params_dict(SCREAMING_SNAKE_CASE						)

  for (src_key, src_param), (dest_key, dest_param) in zip(src_state_dict.items()       ,   dst_state_dict.items()						):
    UpperCAmelCase													=	dest_key
    logger.info(f'''{src_key} -> {dest_key}'''						)
  # if "in1k" was in the model_name it means it must have a classification head (was finetuned)
  if "in1k" in model_name:
    UpperCAmelCase													=	'classifier.1.weight'
    UpperCAmelCase													=	'classifier.1.bias'

  return from_to_ours_keys


def       lowerCamelCase__		(						SCREAMING_SNAKE_CASE      :   Path       ,   SCREAMING_SNAKE_CASE      :   str = None       ,   SCREAMING_SNAKE_CASE      :   bool = True						):
  UpperCAmelCase													=	'imagenet-1k-id2label.json'
  UpperCAmelCase													=	1000

  UpperCAmelCase													=	'huggingface/label-files'
  UpperCAmelCase													=	num_labels
  UpperCAmelCase													=	json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   repo_type='dataset'						)						)       ,   'r'						)						)
  UpperCAmelCase													=	{int(SCREAMING_SNAKE_CASE						): v for k, v in idalabel.items()}

  UpperCAmelCase													=	idalabel
  UpperCAmelCase													=	{v: k for k, v in idalabel.items()}

  UpperCAmelCase													=	partial(SCREAMING_SNAKE_CASE       ,   num_labels=SCREAMING_SNAKE_CASE       ,   idalabel=SCREAMING_SNAKE_CASE       ,   labelaid=SCREAMING_SNAKE_CASE						)

  UpperCAmelCase													=	{
      'regnet-y-10b-seer': ImageNetPreTrainedConfig(
          depths=[2, 7, 17, 1]       ,   hidden_sizes=[2020, 4040, 1_1110, 2_8280]       ,   groups_width=1010						),
      # finetuned on imagenet
      'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig(
          depths=[2, 7, 17, 1]       ,   hidden_sizes=[2020, 4040, 1_1110, 2_8280]       ,   groups_width=1010						),
  }

  # add seer weights logic
  def load_using_classy_vision(SCREAMING_SNAKE_CASE      :   str						) -> Tuple[Dict, Dict]:
    UpperCAmelCase													=	torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE       ,   model_dir=str(SCREAMING_SNAKE_CASE						)       ,   map_location='cpu'						)
    # check if we have a head, if yes add it
    UpperCAmelCase													=	files['classy_state_dict']['base_model']['model']
    return model_state_dict["trunk"], model_state_dict["heads"]

  UpperCAmelCase													=	{
      'regnet-y-10b-seer': partial(
          SCREAMING_SNAKE_CASE       ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch'       ,   ),
      'regnet-y-10b-seer-in1k': partial(
          SCREAMING_SNAKE_CASE       ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch'       ,   ),
  }

  UpperCAmelCase													=	get_from_to_our_keys(SCREAMING_SNAKE_CASE						)

  if not (save_directory / f'''{model_name}.pth''').exists():
    logger.info('Loading original state_dict.'						)
    UpperCAmelCase							,      UpperCAmelCase													=	names_to_from_model[model_name]()
    UpperCAmelCase													=	from_state_dict_trunk
    if "in1k" in model_name:
      # add the head
      UpperCAmelCase													=	{**from_state_dict_trunk, **from_state_dict_head}
    logger.info('Done!'						)

    UpperCAmelCase													=	{}

    UpperCAmelCase													=	list(from_state_dict.keys()						)
    UpperCAmelCase													=	R'\.block.-part.'
    # this is "interesting", so the original checkpoints have `block[0,1]-part` in each key name, we remove it
    for key in from_state_dict.keys():
      # remove the weird "block[0,1]-part" from the key
      UpperCAmelCase													=	re.sub(SCREAMING_SNAKE_CASE       ,   ''       ,   SCREAMING_SNAKE_CASE						)
      # now src_key from the model checkpoints is the one we got from the original model after tracing, so use it to get the correct destination key
      UpperCAmelCase													=	from_to_ours_keys[src_key]
      # store the parameter with our key
      UpperCAmelCase													=	from_state_dict[key]
      not_used_keys.remove(SCREAMING_SNAKE_CASE						)
    # check that all keys have been updated
    assert len(SCREAMING_SNAKE_CASE						) == 0, f'''Some keys where not used {','.join(SCREAMING_SNAKE_CASE						)}'''

    logger.info(f'''The following keys were not used: {','.join(SCREAMING_SNAKE_CASE						)}'''						)

    # save our state dict to disk
    torch.save(SCREAMING_SNAKE_CASE       ,   save_directory / f'''{model_name}.pth'''						)

    del converted_state_dict
  else:
    logger.info('The state_dict was already stored on disk.'						)
  if push_to_hub:
    logger.info(f'''Token is {os.environ['HF_TOKEN']}'''						)
    logger.info('Loading our model.'						)
    # create our model
    UpperCAmelCase													=	names_to_config[model_name]
    UpperCAmelCase													=	RegNetModel
    if "in1k" in model_name:
      UpperCAmelCase													=	RegNetForImageClassification
    UpperCAmelCase													=	our_model_func(SCREAMING_SNAKE_CASE						)
    # place our model to the meta device (so remove all the weights)
    our_model.to(torch.device('meta'						)						)
    logger.info('Loading state_dict in our model.'						)
    # load state dict
    UpperCAmelCase													=	our_model.state_dict().keys()
    PreTrainedModel._load_pretrained_model_low_mem(
        SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   [save_directory / f'''{model_name}.pth''']						)
    logger.info('Finally, pushing!'						)
    # push it to hub
    our_model.push_to_hub(
        repo_path_or_name=save_directory / model_name       ,   commit_message='Add model'       ,   output_dir=save_directory / model_name       ,   )
    UpperCAmelCase													=	384
    # we can use the convnext one
    UpperCAmelCase													=	AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k'       ,   size=SCREAMING_SNAKE_CASE						)
    image_processor.push_to_hub(
        repo_path_or_name=save_directory / model_name       ,   commit_message='Add image processor'       ,   output_dir=save_directory / model_name       ,   )


if __name__ == "__main__":
  _a				: Dict 							=						argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--model_name',
      default=None,
      type=str,
      help=(
          'The name of the model you wish to convert, it must be one of the supported regnet* architecture,'
          ' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.'
      ),
  )
  parser.add_argument(
      '--pytorch_dump_folder_path',
      default=None,
      type=Path,
      required=True,
      help='Path to the output PyTorch model directory.',
  )
  parser.add_argument(
      '--push_to_hub',
      default=True,
      type=bool,
      required=False,
      help='If True, push model and image processor to the hub.',
  )

  _a				: Union[str, Any] 							=						parser.parse_args()

  _a				: Path 							=						args.pytorch_dump_folder_path
  pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
  convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)


