code: 
  
  
  
  
  
  import argparse
  
  import torch
  from saprl.hub import distilhubert
  
  from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging
  
  
  logging.set_verbosity_info()
  lowerCAmelCase_   =   logging.get_logger(__name__)
  
  lowerCAmelCase_   =   {
      "post_extract_proj": "feature_projection.projection",
      "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
      "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
      "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
      "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
      "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
      "self_attn_layer_norm": "encoder.layers.*.layer_norm",
      "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
      "fc2": "encoder.layers.*.feed_forward.output_dense",
      "final_layer_norm": "encoder.layers.*.final_layer_norm",
      "encoder.layer_norm": "encoder.layer_norm",
      "mask_emb": "masked_spec_embed",
  }
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_  )			->						List[Any]:
  
  
  
  
  
  
  
         for attribute in key.split('''.'''  ):
                _snake_case      :							Dict     				=						getattr(_UpperCamelCase      ,		_UpperCamelCase  )
  
         if weight_type is not None:
                _snake_case      :							List[str]     				=						getattr(_UpperCamelCase      ,		_UpperCamelCase  ).shape
         else:
                _snake_case      :							str     				=						hf_pointer.shape
  
         assert hf_shape == value.shape, (
             f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
             f''' {value.shape} for {full_name}'''
         )
  
         if weight_type == "weight":
                _snake_case      :							Tuple     				=						value
         elif weight_type == "weight_g":
                _snake_case      :							Optional[Any]     				=						value
         elif weight_type == "weight_v":
                _snake_case      :							Union[str, Any]     				=						value
         elif weight_type == "bias":
                _snake_case      :							List[Any]     				=						value
         else:
                _snake_case      :							Optional[Any]     				=						value
  
         logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.'''  )
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_  )			->						Optional[Any]:
         _snake_case      :							List[Any]     				=						[]
         _snake_case      :							Tuple     				=						fairseq_model.state_dict()
  
         _snake_case      :							List[str]     				=						hf_model.feature_extractor
  
         for name, value in fairseq_dict.items():
                _snake_case      :							Union[str, Any]     				=						False
                if "conv_layers" in name:
                       load_conv_layer(
                           _UpperCamelCase      ,		_UpperCamelCase      ,		_UpperCamelCase      ,		_UpperCamelCase      ,		hf_model.config.feat_extract_norm == '''group'''      ,		)
                       _snake_case      :							Tuple     				=						True
                else:
                       for key, mapped_key in MAPPING.items():
                              _snake_case      :							str     				=						mapped_key
  
                              if key in name:
                                     _snake_case      :							Dict     				=						True
                                     if "*" in mapped_key:
                                            _snake_case      :							Dict     				=						name.split(_UpperCamelCase  )[0].split('''.'''  )[-2]
                                            _snake_case      :							int     				=						mapped_key.replace('''*'''      ,		_UpperCamelCase  )
                                     if "weight_g" in name:
                                            _snake_case      :							Union[str, Any]     				=						'''weight_g'''
                                     elif "weight_v" in name:
                                            _snake_case      :							Dict     				=						'''weight_v'''
                                     elif "weight" in name:
                                            _snake_case      :							List[str]     				=						'''weight'''
                                     elif "bias" in name:
                                            _snake_case      :							str     				=						'''bias'''
                                     else:
                                            _snake_case      :							List[Any]     				=						None
                                     set_recursively(_UpperCamelCase      ,		_UpperCamelCase      ,		_UpperCamelCase      ,		_UpperCamelCase      ,		_UpperCamelCase  )
                              continue
                if not is_used:
                       unused_weights.append(_UpperCamelCase  )
  
         logger.warning(f'''Unused weights: {unused_weights}'''  )
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_  )			->						Any:
         _snake_case      :							str     				=						full_name.split('''conv_layers.'''  )[-1]
         _snake_case      :							Optional[int]     				=						name.split('''.'''  )
         _snake_case      :							Union[str, Any]     				=						int(items[0]  )
         _snake_case      :							Optional[int]     				=						int(items[1]  )
  
         if type_id == 0:
                if "bias" in name:
                       assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                           f'''{full_name} has size {value.shape}, but'''
                           f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
                       )
                       _snake_case      :							List[str]     				=						value
                       logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''  )
                elif "weight" in name:
                       assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                           f'''{full_name} has size {value.shape}, but'''
                           f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
                       )
                       _snake_case      :							int     				=						value
                       logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''  )
         elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
                if "bias" in name:
                       assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                           f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
                           " found."
                       )
                       _snake_case      :							List[str]     				=						value
                       logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''  )
                elif "weight" in name:
                       assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                           f'''{full_name} has size {value.shape}, but'''
                           f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
                       )
                       _snake_case      :							str     				=						value
                       logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''  )
         else:
                unused_weights.append(_UpperCamelCase  )
  
  
  
  
  def 						A_			(  lowercase_  )			->						Any:
         _snake_case      :							List[Any]     				=						HubertConfig()
         _snake_case      :							Optional[int]     				=						model.config
  
         _snake_case      :							Union[str, Any]     				=						fs_config.activation_dropout
         _snake_case      :							Optional[int]     				=						False
         _snake_case      :							List[Any]     				=						fs_config.attention_dropout
         _snake_case      :							Union[str, Any]     				=						False
         _snake_case      :							Optional[int]     				=						eval(fs_config.extractor_conv_feature_layers  )
         _snake_case      :							Union[str, Any]     				=						[x[0] for x in conv_layers]
         _snake_case      :							Dict     				=						[x[1] for x in conv_layers]
         _snake_case      :							List[str]     				=						[x[2] for x in conv_layers]
         _snake_case      :							List[Any]     				=						'''gelu'''
         _snake_case      :							str     				=						'''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group'''
         _snake_case      :							List[str]     				=						False
         _snake_case      :							List[Any]     				=						0.0
         _snake_case      :							Union[str, Any]     				=						0.0
         _snake_case      :							Dict     				=						fs_config.activation_fn
         _snake_case      :							Dict     				=						fs_config.dropout
         _snake_case      :							Optional[int]     				=						fs_config.encoder_embed_dim
         _snake_case      :							int     				=						0.02
         _snake_case      :							Dict     				=						fs_config.encoder_ffn_embed_dim
         _snake_case      :							Optional[int]     				=						1E-5
         _snake_case      :							Optional[Any]     				=						0.0
         _snake_case      :							List[Any]     				=						fs_config.encoder_attention_heads
         _snake_case      :							Optional[Any]     				=						fs_config.conv_pos_groups
         _snake_case      :							Any     				=						fs_config.conv_pos
         _snake_case      :							Dict     				=						len(_UpperCamelCase  )
         _snake_case      :							Optional[int]     				=						fs_config.encoder_layers
  
         return config
  
  
  
  
  @torch.no_grad()
  def 						A_			(  lowercase_      ,		lowercase_=None  )			->						Optional[int]:
         _snake_case      :							Union[str, Any]     				=						distilhubert().model.model
  
         if config_path is not None:
                _snake_case      :							Optional[int]     				=						HubertConfig.from_pretrained(_UpperCamelCase  )
         else:
                _snake_case      :							List[str]     				=						convert_config(_UpperCamelCase  )
         _snake_case      :							str     				=						model.eval()
  
         _snake_case      :							Dict     				=						WavaVecaFeatureExtractor(
             feature_size=1      ,		sampling_rate=16000      ,		padding_value=0      ,		do_normalize=_UpperCamelCase      ,		return_attention_mask=_UpperCamelCase      ,		)
         _snake_case      :							str     				=						HubertModel(_UpperCamelCase  )
  
         recursively_load_weights(_UpperCamelCase      ,		_UpperCamelCase  )
  
         feature_extractor.save_pretrained(_UpperCamelCase  )
         hf_model.save_pretrained(_UpperCamelCase  )
  
  
  if __name__ == "__main__":
     lowerCAmelCase_   =   argparse.ArgumentParser()
     parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
     parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
     lowerCAmelCase_   =   parser.parse_args()
     convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)
  
  
  
  
  
  
  
style_context: 
  
  
  
  
  
  import unittest
  
  import numpy as np
  
  from transformers.testing_utils import require_torch, require_vision
  from transformers.utils import is_torch_available, is_vision_available
  
  from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
  
  
  if is_torch_available():
     import torch
  
  if is_vision_available():
     from PIL import Image
  
     from transformers import ConvNextImageProcessor
  
  class 				A    (unittest.TestCase				):
  
  
  
        def __init__(					self     ,  lowercase_     ,  lowercase_=7     ,  lowercase_=3     ,  lowercase_=18     ,  lowercase_=30     ,  lowercase_=400     ,  lowercase_=True     ,  lowercase_=None     ,  lowercase_=0.875     ,  lowercase_=True     ,  lowercase_=[0.5, 0.5, 0.5]     ,  lowercase_=[0.5, 0.5, 0.5]     ,  )      ->   List[str]:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Tuple     				=						size if size is not None else {'''shortest_edge''': 20}
               _snake_case      :							List[Any]     				=						parent
               _snake_case      :							Optional[int]     				=						batch_size
               _snake_case      :							str     				=						num_channels
               _snake_case      :							Union[str, Any]     				=						image_size
               _snake_case      :							Optional[Any]     				=						min_resolution
               _snake_case      :							Union[str, Any]     				=						max_resolution
               _snake_case      :							Tuple     				=						do_resize
               _snake_case      :							List[Any]     				=						size
               _snake_case      :							Optional[int]     				=						crop_pct
               _snake_case      :							Any     				=						do_normalize
               _snake_case      :							Optional[int]     				=						image_mean
               _snake_case      :							Union[str, Any]     				=						image_std
  
  
  
        def    __a (					self					)      ->   str:
  
  
  
               '''simple docstring'''
  
               return {
                   "image_mean": self.image_mean,
                   "image_std": self.image_std,
                   "do_normalize": self.do_normalize,
                   "do_resize": self.do_resize,
                   "size": self.size,
                   "crop_pct": self.crop_pct,
               }
  
  
  @require_torch
  @require_vision
  class 				A    (__UpperCAmelCase       ,unittest.TestCase				):
        _SCREAMING_SNAKE_CASE					=							ConvNextImageProcessor if is_vision_available() else None
  
  
  
        def    __a (					self					)      ->   Dict:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							List[Any]     				=						ConvNextImageProcessingTester(self					)
  
  
  
        @property
        def    __a (					self					)      ->   Dict:
  
  
  
               '''simple docstring'''
  
               return self.image_processor_tester.prepare_image_processor_dict()
  
  
  
        def    __a (					self					)      ->   str:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							List[Any]     				=						self.image_processing_class(**self.image_processor_dict					)
               self.assertTrue(hasattr(lowercase_     ,  '''do_resize'''					)					)
               self.assertTrue(hasattr(lowercase_     ,  '''size'''					)					)
               self.assertTrue(hasattr(lowercase_     ,  '''crop_pct'''					)					)
               self.assertTrue(hasattr(lowercase_     ,  '''do_normalize'''					)					)
               self.assertTrue(hasattr(lowercase_     ,  '''image_mean'''					)					)
               self.assertTrue(hasattr(lowercase_     ,  '''image_std'''					)					)
  
  
  
        def    __a (					self					)      ->   List[Any]:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							int     				=						self.image_processing_class.from_dict(self.image_processor_dict					)
               self.assertEqual(image_processor.size     ,  {'''shortest_edge''': 20}					)
  
               _snake_case      :							Tuple     				=						self.image_processing_class.from_dict(self.image_processor_dict     ,  size=42					)
               self.assertEqual(image_processor.size     ,  {'''shortest_edge''': 42}					)
  
  
  
        def    __a (					self					)      ->   List[Any]:
  
  
  
               '''simple docstring'''
  
               pass
  
  
  
        def    __a (					self					)      ->   int:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Tuple     				=						self.image_processing_class(**self.image_processor_dict					)
               # create random PIL images
               _snake_case      :							List[str]     				=						prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=lowercase_					)
               for image in image_inputs:
                      self.assertIsInstance(lowercase_     ,  Image.Image					)
  
               # Test not batched input
               _snake_case      :							List[str]     				=						image_processing(image_inputs[0]     ,  return_tensors='''pt'''					).pixel_values
               self.assertEqual(
                   encoded_images.shape     ,  (
                       1,
                       self.image_processor_tester.num_channels,
                       self.image_processor_tester.size['''shortest_edge'''],
                       self.image_processor_tester.size['''shortest_edge'''],
                   )     ,  )
  
               # Test batched
               _snake_case      :							int     				=						image_processing(lowercase_     ,  return_tensors='''pt'''					).pixel_values
               self.assertEqual(
                   encoded_images.shape     ,  (
                       self.image_processor_tester.batch_size,
                       self.image_processor_tester.num_channels,
                       self.image_processor_tester.size['''shortest_edge'''],
                       self.image_processor_tester.size['''shortest_edge'''],
                   )     ,  )
  
  
  
        def    __a (					self					)      ->   Dict:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Tuple     				=						self.image_processing_class(**self.image_processor_dict					)
               # create random numpy tensors
               _snake_case      :							Tuple     				=						prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=lowercase_     ,  numpify=lowercase_					)
               for image in image_inputs:
                      self.assertIsInstance(lowercase_     ,  np.ndarray					)
  
               # Test not batched input
               _snake_case      :							List[str]     				=						image_processing(image_inputs[0]     ,  return_tensors='''pt'''					).pixel_values
               self.assertEqual(
                   encoded_images.shape     ,  (
                       1,
                       self.image_processor_tester.num_channels,
                       self.image_processor_tester.size['''shortest_edge'''],
                       self.image_processor_tester.size['''shortest_edge'''],
                   )     ,  )
  
               # Test batched
               _snake_case      :							Union[str, Any]     				=						image_processing(lowercase_     ,  return_tensors='''pt'''					).pixel_values
               self.assertEqual(
                   encoded_images.shape     ,  (
                       self.image_processor_tester.batch_size,
                       self.image_processor_tester.num_channels,
                       self.image_processor_tester.size['''shortest_edge'''],
                       self.image_processor_tester.size['''shortest_edge'''],
                   )     ,  )
  
  
  
        def    __a (					self					)      ->   Union[str, Any]:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Union[str, Any]     				=						self.image_processing_class(**self.image_processor_dict					)
               # create random PyTorch tensors
               _snake_case      :							Dict     				=						prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=lowercase_     ,  torchify=lowercase_					)
               for image in image_inputs:
                      self.assertIsInstance(lowercase_     ,  torch.Tensor					)
  
               # Test not batched input
               _snake_case      :							Union[str, Any]     				=						image_processing(image_inputs[0]     ,  return_tensors='''pt'''					).pixel_values
               self.assertEqual(
                   encoded_images.shape     ,  (
                       1,
                       self.image_processor_tester.num_channels,
                       self.image_processor_tester.size['''shortest_edge'''],
                       self.image_processor_tester.size['''shortest_edge'''],
                   )     ,  )
  
               # Test batched
               _snake_case      :							List[Any]     				=						image_processing(lowercase_     ,  return_tensors='''pt'''					).pixel_values
               self.assertEqual(
                   encoded_images.shape     ,  (
                       self.image_processor_tester.batch_size,
                       self.image_processor_tester.num_channels,
                       self.image_processor_tester.size['''shortest_edge'''],
                       self.image_processor_tester.size['''shortest_edge'''],
                   )     ,  )
  
  
  
  
  
  
  