






'''simple docstring'''






import argparse

import torch

# Step 1. clone https://github.com/microsoft/unilm
# Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd
# Step 3. cd unilm
# Step 4. ln -s $(realpath wavlm/modules.py) ./  # create simlink
# import classes
from unilm.wavlm.WavLM import WavLM as WavLMOrig
from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig

from transformers import WavLMConfig, WavLMModel, logging


logging.set_verbosity_info()
__A    	=   logging.get_logger(__name__)

__A    	=   {
    '''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.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''',
    '''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''',
    '''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''',
    '''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''',
    '''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
    '''quantizer.weight_proj''': '''quantizer.weight_proj''',
    '''quantizer.vars''': '''quantizer.codevectors''',
    '''project_q''': '''project_q''',
    '''final_proj''': '''project_hid''',
    '''w2v_encoder.proj''': '''ctc_proj''',
    '''mask_emb''': '''masked_spec_embed''',
}
__A    	=   [
    '''ctc_proj''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
]




def        _SCREAMING_SNAKE_CASE  (				A  :       int  ,		A  :       List[str]  ,		A  :       Optional[Any]  ,		A  :       int  ,		A  :       Tuple  )    -> Tuple:







   """simple docstring"""




   for attribute in key.split('.'  ):
      __snake_case				:      str     							= getattr(__a  ,		__a  )

   if weight_type is not None:
      __snake_case				:      Dict     							= getattr(__a  ,		__a  ).shape
   else:
      __snake_case				:      Optional[int]     							= 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				:      Union[str, Any]     							= value
   elif weight_type == "weight_g":
      __snake_case				:      Any     							= value
   elif weight_type == "weight_v":
      __snake_case				:      int     							= value
   elif weight_type == "bias":
      __snake_case				:      Union[str, Any]     							= value
   else:
      __snake_case				:      Any     							= value

   logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}."""  )




def        _SCREAMING_SNAKE_CASE  (				A  :       Dict  ,		A  :       Union[str, Any]  )    -> List[Any]:







   """simple docstring"""
   __snake_case				:      Dict     							= []
   __snake_case				:      List[str]     							= fairseq_model.state_dict()

   __snake_case				:      Union[str, Any]     							= hf_model.feature_extractor

   for name, value in fairseq_dict.items():
      __snake_case				:      Tuple     							= False
      if "conv_layers" in name:
         load_conv_layer(
             __a  ,		__a  ,		__a  ,		__a  ,		hf_model.config.feat_extract_norm == 'group'  ,		)
         __snake_case				:      Optional[int]     							= True
      else:
         for key, mapped_key in MAPPING.items():
            if key in name or key.split('w2v_model.'  )[-1] == name.split('.'  )[0]:
               __snake_case				:      Optional[int]     							= True
               if "*" in mapped_key:
                  __snake_case				:      Union[str, Any]     							= name.split(__a  )[0].split('.'  )[-2]
                  __snake_case				:      Dict     							= mapped_key.replace('*'  ,		__a  )
               if "weight_g" in name:
                  __snake_case				:      List[Any]     							= 'weight_g'
               elif "weight_v" in name:
                  __snake_case				:      Any     							= 'weight_v'
               elif "bias" in name and "relative_attention_bias" not in name:
                  __snake_case				:      Tuple     							= 'bias'
               elif "weight" in name:
                  # TODO: don't match quantizer.weight_proj
                  __snake_case				:      List[str]     							= 'weight'
               else:
                  __snake_case				:      List[str]     							= None

               set_recursively(__a  ,		__a  ,		__a  ,		__a  ,		__a  )
            continue
      if not is_used:
         unused_weights.append(__a  )

   logger.warning(F"""Unused weights: {unused_weights}"""  )




def        _SCREAMING_SNAKE_CASE  (				A  :       Any  ,		A  :       str  ,		A  :       Tuple  ,		A  :       Optional[Any]  ,		A  :       Optional[Any]  )    -> int:







   """simple docstring"""
   __snake_case				:      Optional[int]     							= full_name.split('conv_layers.'  )[-1]
   __snake_case				:      Dict     							= 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				:      Dict     							= 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				:      Optional[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				:      int     							= 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				:      Dict     							= value
         logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""  )
   else:
      unused_weights.append(__a  )




@torch.no_grad()
def        _SCREAMING_SNAKE_CASE  (				A  :       List[Any]  ,		A  :       Any  ,		A  :       Union[str, Any]=None  )    -> Any:







   """simple docstring"""
   __snake_case				:      Tuple     							= torch.load(__a  )
   __snake_case				:      Any     							= WavLMConfigOrig(checkpoint['cfg']  )
   __snake_case				:      Union[str, Any]     							= WavLMOrig(__a  )
   model.load_state_dict(checkpoint['model']  )
   model.eval()

   if config_path is not None:
      __snake_case				:      Dict     							= WavLMConfig.from_pretrained(__a  )
   else:
      __snake_case				:      str     							= WavLMConfig()

   __snake_case				:      str     							= WavLMModel(__a  )

   recursively_load_weights(__a  ,		__a  )

   hf_wavlm.save_pretrained(__a  )


if __name__ == "__main__":
      __A    	=   argparse.ArgumentParser()
      parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
      parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
      parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
      __A    	=   parser.parse_args()
      convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)







'''simple docstring'''






import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
      from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
      from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
      from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


__A    	=   DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

__A    	=   '''main'''
# Default branch name
__A    	=   '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A    	=   '''aaaaaaa'''
# This commit does not exist, so we should 404.

__A    	=   '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A    	=   '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''




@contextlib.contextmanager
def        _SCREAMING_SNAKE_CASE  (				)    -> List[Any]:







   """simple docstring"""
   print('Welcome!'  )
   yield
   print('Bye!'  )




@contextlib.contextmanager
def        _SCREAMING_SNAKE_CASE  (				)    -> Optional[Any]:







   """simple docstring"""
   print('Bonjour!'  )
   yield
   print('Au revoir!'  )




class a_    (    unittest.TestCase							):







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      assert transformers.__spec__ is not None
      assert importlib.util.find_spec('transformers') is not None




class a_    (    unittest.TestCase							):







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      int:
      """simple docstring"""






      with ContextManagers([]):
         print('Transformers are awesome!')
      # The print statement adds a new line at the end of the output
      self.assertEqual(mock_stdout.getvalue()					,   'Transformers are awesome!\n')







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      List[str]:
      """simple docstring"""






      with ContextManagers([context_en()]):
         print('Transformers are awesome!')
      # The output should be wrapped with an English welcome and goodbye
      self.assertEqual(mock_stdout.getvalue()					,   'Welcome!\nTransformers are awesome!\nBye!\n')







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      Tuple:
      """simple docstring"""






      with ContextManagers([context_fr(), context_en()]):
         print('Transformers are awesome!')
      # The output should be wrapped with an English and French welcome and goodbye
      self.assertEqual(mock_stdout.getvalue()					,   'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')







   @require_torch
   def     SCREAMING_SNAKE_CASE__					(self)			->      Union[str, Any]:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   ['labels'])
      self.assertEqual(find_labels(__a)					,   ['labels', 'next_sentence_label'])
      self.assertEqual(find_labels(__a)					,   ['start_positions', 'end_positions'])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   ['labels'])







   @require_tf
   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   ['labels'])
      self.assertEqual(find_labels(__a)					,   ['labels', 'next_sentence_label'])
      self.assertEqual(find_labels(__a)					,   ['start_positions', 'end_positions'])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   ['labels'])







   @require_flax
   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   [])
      self.assertEqual(find_labels(__a)					,   [])
      self.assertEqual(find_labels(__a)					,   [])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   [])