code: 
  
  
  
  
  
  '''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 							__snake_case    :
  	__lowerCAmelCase						=     42
  	__lowerCAmelCase						=     field(default_factory=__magic_name__       )
  	__lowerCAmelCase						=     field(default_factory=__magic_name__       )
  	__lowerCAmelCase						=     field(default_factory=__magic_name__       )
  
  
  
  
  
  	def      _snake_case      (		self			,					UpperCamelCase_			,					UpperCamelCase_			,					UpperCamelCase_			,					UpperCamelCase_		)			->		Optional[int]:
  		snake_case__  					=      len(list(m.modules()		)		) == 1 or isinstance(UpperCamelCase_			,					nn.Convad		) or isinstance(UpperCamelCase_			,					nn.BatchNormad		)
  		if has_not_submodules:
  			self.traced.append(UpperCamelCase_		)
  			snake_case__  					=      m
  
  
  
  
  
  	def __call__(		self			,					UpperCamelCase_		)			->		Optional[int]:
  		for name, m in self.module.named_modules():
  			self.handles.append(m.register_forward_hook(partial(self._forward_hook			,					name=UpperCamelCase_		)		)		)
  		self.module(UpperCamelCase_		)
  		[x.remove() for x in self.handles]
  		return self
  
  
  
  
  
  	@property
  	def      _snake_case      (		self		)			->		Optional[int]:
  		# 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 							__snake_case    (				nn.Module       ):
  
  
  
  
  
  	def __init__(		self			,					UpperCamelCase_		)			->		int:
  		super().__init__()
  
  		snake_case__  					=      []
  		# - 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}'''
  			snake_case__  					=      len(UpperCamelCase_		) + 1
  			feature_blocks.append((F'''res{block_index}''', v)		)
  
  		snake_case__  					=      nn.ModuleDict(UpperCamelCase_		)
  
  
  
  
  
  	def      _snake_case      (		self			,					UpperCamelCase_		)			->		List[str]:
  		return get_trunk_forward_outputs(
  		    UpperCamelCase_			,					out_feat_keys=UpperCamelCase_			,					feature_blocks=self._feature_blocks			,					)
  
  
  
  
  
  
  class 							__snake_case    (				__magic_name__       ):
  
  
  
  
  
  	def      _snake_case      (		self		)			->		List[str]:
  		return [(8, 2, 2, 8, 1.0), (8, 2, 7, 8, 1.0), (8, 2, 17, 8, 1.0), (8, 2, 1, 8, 1.0)]
  
  
  
  
  
  def 	__lowerCamelCase (  UpperCAmelCase_       )      ->Dict[str, str]:
  	snake_case__  					=      RegNetConfig(depths=[2, 7, 17, 1]				,							hidden_sizes=[8, 8, 8, 8]				,							groups_width=8       )
  	if "in1k" in model_name:
  		snake_case__  					=      RegNetForImageClassification(UpperCAmelCase_       )
  	else:
  		snake_case__  					=      RegNetModel(UpperCAmelCase_       )
  	# create from model (with small weights)
  	snake_case__  					=      FakeRegNetVisslWrapper(
  	    RegNet(FakeRegNetParams(depth=27				,							group_width=10_10				,							w_a=17_44				,							w_a=620.83				,							w_m=2.52       )       )       )
  
  	with torch.no_grad():
  		snake_case__  					=      from_model.eval()
  		snake_case__  					=      our_model.eval()
  
  		snake_case__  					=      torch.randn((1, 3, 32, 32)       )
  		# trace both
  		snake_case__  					=      Tracker(UpperCAmelCase_       )
  		snake_case__  					=      dest_tracker(UpperCAmelCase_       ).parametrized
  
  		pprint(dest_tracker.nameamodule       )
  		snake_case__  					=      Tracker(UpperCAmelCase_       )
  		snake_case__  					=      src_tracker(UpperCAmelCase_       ).parametrized
  
  	# convert the keys -> module dict to keys -> params
  	def to_params_dict(UpperCAmelCase_       ):
  		snake_case__  					=      OrderedDict()
  		for name, module in dict_with_modules.items():
  			for param_name, param in module.state_dict().items():
  				snake_case__  					=      param
  		return params_dict
  
  	snake_case__  					=      {}
  
  	snake_case__  					=      to_params_dict(UpperCAmelCase_       )
  	snake_case__  					=      to_params_dict(UpperCAmelCase_       )
  
  	for (src_key, src_param), (dest_key, dest_param) in zip(src_state_dict.items()				,							dst_state_dict.items()       ):
  		snake_case__  					=      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:
  		snake_case__  					=      'classifier.1.weight'
  		snake_case__  					=      'classifier.1.bias'
  
  	return from_to_ours_keys
  
  
  
  
  def 	__lowerCamelCase (  UpperCAmelCase_				,							UpperCAmelCase_ = None				,							UpperCAmelCase_ = True       )      ->Union[str, Any]:
  	snake_case__  					=      'imagenet-1k-id2label.json'
  	snake_case__  					=      10_00
  
  	snake_case__  					=      'huggingface/label-files'
  	snake_case__  					=      num_labels
  	snake_case__  					=      json.load(open(cached_download(hf_hub_url(UpperCAmelCase_				,							UpperCAmelCase_				,							repo_type='dataset'       )       )				,							'r'       )       )
  	snake_case__  					=      {int(UpperCAmelCase_       ): v for k, v in idalabel.items()}
  
  	snake_case__  					=      idalabel
  	snake_case__  					=      {v: k for k, v in idalabel.items()}
  
  	snake_case__  					=      partial(UpperCAmelCase_				,							num_labels=UpperCAmelCase_				,							idalabel=UpperCAmelCase_				,							labelaid=UpperCAmelCase_       )
  
  	snake_case__  					=      {
  	    'regnet-y-10b-seer': ImageNetPreTrainedConfig(
  	        depths=[2, 7, 17, 1]				,							hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80]				,							groups_width=10_10       ),
  	    # finetuned on imagenet
  	    'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig(
  	        depths=[2, 7, 17, 1]				,							hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80]				,							groups_width=10_10       ),
  	}
  
  	# add seer weights logic
  	def load_using_classy_vision(UpperCAmelCase_       ) -> Tuple[Dict, Dict]:
  		snake_case__  					=      torch.hub.load_state_dict_from_url(UpperCAmelCase_				,							model_dir=str(UpperCAmelCase_       )				,							map_location='cpu'       )
  		# check if we have a head, if yes add it
  		snake_case__  					=      files['classy_state_dict']['base_model']['model']
  		return model_state_dict["trunk"], model_state_dict["heads"]
  
  	snake_case__  					=      {
  	    'regnet-y-10b-seer': partial(
  	        UpperCAmelCase_				,							'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch'				,							),
  	    'regnet-y-10b-seer-in1k': partial(
  	        UpperCAmelCase_				,							'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch'				,							),
  	}
  
  	snake_case__  					=      get_from_to_our_keys(UpperCAmelCase_       )
  
  	if not (save_directory / f'''{model_name}.pth''').exists():
  		logger.info('Loading original state_dict.'       )
  		snake_case__					,     snake_case__  					=      names_to_from_model[model_name]()
  		snake_case__  					=      from_state_dict_trunk
  		if "in1k" in model_name:
  			# add the head
  			snake_case__  					=      {**from_state_dict_trunk, **from_state_dict_head}
  		logger.info('Done!'       )
  
  		snake_case__  					=      {}
  
  		snake_case__  					=      list(from_state_dict.keys()       )
  		snake_case__  					=      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
  			snake_case__  					=      re.sub(UpperCAmelCase_				,							''				,							UpperCAmelCase_       )
  			# 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
  			snake_case__  					=      from_to_ours_keys[src_key]
  			# store the parameter with our key
  			snake_case__  					=      from_state_dict[key]
  			not_used_keys.remove(UpperCAmelCase_       )
  		# check that all keys have been updated
  		assert len(UpperCAmelCase_       ) == 0, f'''Some keys where not used {','.join(UpperCAmelCase_       )}'''
  
  		logger.info(f'''The following keys were not used: {','.join(UpperCAmelCase_       )}'''       )
  
  		# save our state dict to disk
  		torch.save(UpperCAmelCase_				,							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
  		snake_case__  					=      names_to_config[model_name]
  		snake_case__  					=      RegNetModel
  		if "in1k" in model_name:
  			snake_case__  					=      RegNetForImageClassification
  		snake_case__  					=      our_model_func(UpperCAmelCase_       )
  		# 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
  		snake_case__  					=      our_model.state_dict().keys()
  		PreTrainedModel._load_pretrained_model_low_mem(
  		    UpperCAmelCase_				,							UpperCAmelCase_				,							[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				,							)
  		snake_case__  					=      3_84
  		# we can use the convnext one
  		snake_case__  					=      AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k'				,							size=UpperCAmelCase_       )
  		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__				: Tuple									=    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__				: List[str]									=    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)
  
  
  
  
style_context: 
  
  
  
  
  
  '''simple docstring'''
  
  
  
  
  import shutil
  import tempfile
  import unittest
  
  import pytest
  
  from transformers import WhisperTokenizer, is_speech_available
  from transformers.testing_utils import require_sentencepiece, require_torch, require_torchaudio
  
  from .test_feature_extraction_whisper import floats_list
  
  
  if is_speech_available():
  			from transformers import WhisperFeatureExtractor, WhisperProcessor
  
  
  a__				: Tuple									=    5_0358
  a__				: str									=    5_0362
  
  
  
  
  
  
  @require_torch
  @require_torchaudio
  @require_sentencepiece
  class 							__snake_case    (				unittest.TestCase       ):
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Dict:
  		snake_case__  					=      'openai/whisper-small.en'
  		snake_case__  					=      tempfile.mkdtemp()
  
  
  
  
  
  	def      _snake_case      (		self			,					**UpperCamelCase_		)			->		Optional[int]:
  		return WhisperTokenizer.from_pretrained(self.checkpoint			,					**UpperCamelCase_		)
  
  
  
  
  
  	def      _snake_case      (		self			,					**UpperCamelCase_		)			->		Any:
  		return WhisperFeatureExtractor.from_pretrained(self.checkpoint			,					**UpperCamelCase_		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Tuple:
  		shutil.rmtree(self.tmpdirname		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Any:
  		snake_case__  					=      self.get_tokenizer()
  		snake_case__  					=      self.get_feature_extractor()
  
  		snake_case__  					=      WhisperProcessor(tokenizer=UpperCamelCase_			,					feature_extractor=UpperCamelCase_		)
  
  		processor.save_pretrained(self.tmpdirname		)
  		snake_case__  					=      WhisperProcessor.from_pretrained(self.tmpdirname		)
  
  		self.assertEqual(processor.tokenizer.get_vocab()			,					tokenizer.get_vocab()		)
  		self.assertIsInstance(processor.tokenizer			,					UpperCamelCase_		)
  
  		self.assertEqual(processor.feature_extractor.to_json_string()			,					feature_extractor.to_json_string()		)
  		self.assertIsInstance(processor.feature_extractor			,					UpperCamelCase_		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Dict:
  		snake_case__  					=      WhisperProcessor(tokenizer=self.get_tokenizer()			,					feature_extractor=self.get_feature_extractor()		)
  		processor.save_pretrained(self.tmpdirname		)
  
  		snake_case__  					=      self.get_tokenizer(bos_token='(BOS)'			,					eos_token='(EOS)'		)
  		snake_case__  					=      self.get_feature_extractor(do_normalize=UpperCamelCase_			,					padding_value=1.0		)
  
  		snake_case__  					=      WhisperProcessor.from_pretrained(
  		    self.tmpdirname			,					bos_token='(BOS)'			,					eos_token='(EOS)'			,					do_normalize=UpperCamelCase_			,					padding_value=1.0		)
  
  		self.assertEqual(processor.tokenizer.get_vocab()			,					tokenizer_add_kwargs.get_vocab()		)
  		self.assertIsInstance(processor.tokenizer			,					UpperCamelCase_		)
  
  		self.assertEqual(processor.feature_extractor.to_json_string()			,					feature_extractor_add_kwargs.to_json_string()		)
  		self.assertIsInstance(processor.feature_extractor			,					UpperCamelCase_		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		List[str]:
  		snake_case__  					=      self.get_feature_extractor()
  		snake_case__  					=      self.get_tokenizer()
  
  		snake_case__  					=      WhisperProcessor(tokenizer=UpperCamelCase_			,					feature_extractor=UpperCamelCase_		)
  
  		snake_case__  					=      floats_list((3, 1000)		)
  
  		snake_case__  					=      feature_extractor(UpperCamelCase_			,					return_tensors='np'		)
  		snake_case__  					=      processor(UpperCamelCase_			,					return_tensors='np'		)
  
  		for key in input_feat_extract.keys():
  			self.assertAlmostEqual(input_feat_extract[key].sum()			,					input_processor[key].sum()			,					delta=1E-2		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Union[str, Any]:
  		snake_case__  					=      self.get_feature_extractor()
  		snake_case__  					=      self.get_tokenizer()
  
  		snake_case__  					=      WhisperProcessor(tokenizer=UpperCamelCase_			,					feature_extractor=UpperCamelCase_		)
  
  		snake_case__  					=      'This is a test string'
  
  		snake_case__  					=      processor(text=UpperCamelCase_		)
  
  		snake_case__  					=      tokenizer(UpperCamelCase_		)
  
  		for key in encoded_tok.keys():
  			self.assertListEqual(encoded_tok[key]			,					encoded_processor[key]		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Tuple:
  		snake_case__  					=      self.get_feature_extractor()
  		snake_case__  					=      self.get_tokenizer()
  
  		snake_case__  					=      WhisperProcessor(tokenizer=UpperCamelCase_			,					feature_extractor=UpperCamelCase_		)
  
  		snake_case__  					=      [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
  
  		snake_case__  					=      processor.batch_decode(UpperCamelCase_		)
  		snake_case__  					=      tokenizer.batch_decode(UpperCamelCase_		)
  
  		self.assertListEqual(UpperCamelCase_			,					UpperCamelCase_		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		List[str]:
  		snake_case__  					=      self.get_feature_extractor()
  		snake_case__  					=      self.get_tokenizer()
  
  		snake_case__  					=      WhisperProcessor(tokenizer=UpperCamelCase_			,					feature_extractor=UpperCamelCase_		)
  
  		self.assertListEqual(
  		    processor.model_input_names			,					feature_extractor.model_input_names			,					msg='`processor` and `feature_extractor` model input names do not match'			,					)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Dict:
  		snake_case__  					=      self.get_feature_extractor()
  		snake_case__  					=      self.get_tokenizer()
  
  		snake_case__  					=      WhisperProcessor(tokenizer=UpperCamelCase_			,					feature_extractor=UpperCamelCase_		)
  		snake_case__  					=      processor.get_decoder_prompt_ids(task='transcribe'			,					no_timestamps=UpperCamelCase_		)
  
  		self.assertIsInstance(UpperCamelCase_			,					UpperCamelCase_		)
  		for ids in forced_decoder_ids:
  			self.assertIsInstance(UpperCamelCase_			,					(list, tuple)		)
  
  		snake_case__  					=      [TRANSCRIBE, NOTIMESTAMPS]
  		self.assertListEqual([ids[-1] for ids in forced_decoder_ids]			,					UpperCamelCase_		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		List[str]:
  		snake_case__  					=      WhisperProcessor(tokenizer=self.get_tokenizer()			,					feature_extractor=self.get_feature_extractor()		)
  		snake_case__  					=      processor.get_prompt_ids('Mr. Quilter'		)
  		snake_case__  					=      processor.tokenizer.decode(UpperCamelCase_		)
  
  		self.assertListEqual(prompt_ids.tolist()			,					[5_0360, 1770, 13, 2264, 346, 353]		)
  		self.assertEqual(UpperCamelCase_			,					'<|startofprev|> Mr. Quilter'		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		Dict:
  		snake_case__  					=      WhisperProcessor(tokenizer=self.get_tokenizer()			,					feature_extractor=self.get_feature_extractor()		)
  		snake_case__  					=      processor.get_prompt_ids(''		)
  		snake_case__  					=      processor.tokenizer.decode(UpperCamelCase_		)
  
  		self.assertListEqual(prompt_ids.tolist()			,					[5_0360, 220]		)
  		self.assertEqual(UpperCamelCase_			,					'<|startofprev|> '		)
  
  
  
  
  
  	def      _snake_case      (		self		)			->		int:
  		snake_case__  					=      WhisperProcessor(tokenizer=self.get_tokenizer()			,					feature_extractor=self.get_feature_extractor()		)
  
  		def _test_prompt_error_raised_helper(UpperCamelCase_			,					UpperCamelCase_		):
  			with pytest.raises(UpperCamelCase_		) as excinfo:
  				processor.get_prompt_ids(UpperCamelCase_		)
  			snake_case__  					=      F'''Encountered text in the prompt corresponding to disallowed special token: {special_token}.'''
  			self.assertEqual(UpperCamelCase_			,					str(excinfo.value		)		)
  
  		_test_prompt_error_raised_helper('<|startofprev|> test'			,					'<|startofprev|>'		)
  		_test_prompt_error_raised_helper('test <|notimestamps|>'			,					'<|notimestamps|>'		)
  		_test_prompt_error_raised_helper('test <|zh|> test <|transcribe|>'			,					'<|zh|>'		)
  
  
  
  