




'''simple docstring'''


import argparse
import os
from functools import reduce

import fairseq
import torch
from datasets import load_dataset

from transformers import WavaVecaProcessor, logging
from transformers.models.dataavec.configuration_dataavec_audio import DataaVecAudioConfig

# Copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_audio.py
from transformers.models.dataavec.dataavec_audio import DataaVecAudioModel as Dummy  # noqa: F401
from transformers.models.dataavec.modeling_dataavec_audio import DataaVecAudioForCTC, DataaVecAudioModel


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

UpperCamelCase			     =					{
    '''post_extract_proj''': '''feature_projection.projection''',
    '''models.0.layer_norm''': '''feature_projection.layer_norm''',
    '''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''',
    '''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
    '''w2v_encoder.proj''': '''lm_head''',
    '''mask_emb''': '''masked_spec_embed''',
}
UpperCamelCase			     =					[
    '''lm_head''',
]
def 					SCREAMING_SNAKE_CASE(   __lowercase		,				__lowercase		,				__lowercase		,				__lowercase		,				__lowercase	)			-> Any:
     for attribute in key.split('''.'''	):
          A:		Union[str, Any]          =		getattr(__lowercase		,				__lowercase	)

     if weight_type is not None:
          A:		Tuple          =		getattr(__lowercase		,				__lowercase	).shape
     else:
          A:		Optional[int]          =		hf_pointer.shape

     if hf_shape != value.shape:
          raise ValueError(
              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":
          A:		int          =		value
     elif weight_type == "weight_g":
          A:		Any          =		value
     elif weight_type == "weight_v":
          A:		str          =		value
     elif weight_type == "bias":
          A:		List[str]          =		value
     else:
          A:		str          =		value

     logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}."""	)
def 					SCREAMING_SNAKE_CASE(   __lowercase		,				__lowercase		,				__lowercase	)			-> Dict:
     A:		Optional[int]          =		[]
     A:		Tuple          =		fairseq_model.state_dict()

     if not is_headless:
          A:		int          =		hf_model.dataavec_audio.feature_extractor
          A:		Dict          =		hf_model.dataavec_audio.encoder.pos_conv_embed

     else:
          A:		str          =		hf_model.feature_extractor
          A:		Tuple          =		hf_model.encoder.pos_conv_embed

     for name, value in fairseq_dict.items():
          A:		int          =		False
          if "conv_layers" in name:
               load_conv_layer(
                   __lowercase		,				__lowercase		,				__lowercase		,				__lowercase		,				)
               A:		List[Any]          =		True
          elif "pos_conv" in name:
               load_pos_conv_layer(
                   __lowercase		,				__lowercase		,				__lowercase		,				__lowercase		,				)
               A:		Union[str, Any]          =		True
          else:
               for key, mapped_key in MAPPING.items():
                    if not is_headless:
                         A:		str          =		'''data2vec_audio.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
                    if key in name or key.split('''w2v_model.'''	)[-1] == name.split('''.'''	)[0]:
                         A:		Optional[int]          =		True
                         if "*" in mapped_key:
                              A:		Any          =		name.split(__lowercase	)[0].split('''.'''	)[-2]
                              A:		Any          =		mapped_key.replace('''*'''		,				__lowercase	)
                         if "weight_g" in name:
                              A:		List[Any]          =		'''weight_g'''
                         elif "weight_v" in name:
                              A:		List[Any]          =		'''weight_v'''
                         elif "bias" in name:
                              A:		int          =		'''bias'''
                         elif "weight" in name:
                              # TODO: don't match quantizer.weight_proj
                              A:		int          =		'''weight'''
                         else:
                              A:		List[Any]          =		None
                         set_recursively(__lowercase		,				__lowercase		,				__lowercase		,				__lowercase		,				__lowercase	)
                    continue
          if not is_used:
               unused_weights.append(__lowercase	)

     logger.warning(F"""Unused weights: {unused_weights}"""	)
def 					SCREAMING_SNAKE_CASE(   __lowercase		,				__lowercase	)			-> str:
     A:		int          =		path.split('''.'''	)
     return reduce(__lowercase		,				__lowercase		,				__lowercase	)
def 					SCREAMING_SNAKE_CASE(   __lowercase		,				__lowercase		,				__lowercase		,				__lowercase	)			-> Optional[Any]:
     A:		Tuple          =		access_by_string(__lowercase		,				__lowercase	)
     A:		Tuple          =		hf_weight.data

     if fsq_value.shape != hf_value.shape:
          raise ValueError(F"""{full_name} has size {fsq_value.shape}, but {hf_value.shape} was found."""	)
     A:		List[Any]          =		fsq_value
     logger.info(F"""{full_name} was correctly initialized from {hf_weight_path}."""	)
def 					SCREAMING_SNAKE_CASE(   __lowercase		,				__lowercase		,				__lowercase		,				__lowercase	)			-> List[Any]:
     A:		List[Any]          =		full_name.split('''conv_layers.'''	)[-1]
     A:		List[str]          =		name.split('''.'''	)
     A:		Tuple          =		int(items[0]	)
     A:		Optional[int]          =		int(items[1]	)

     A:		List[str]          =		name.split('''.'''	)[-1]
     if type_id == 0:
          A:		Optional[Any]          =		'''conv'''
     elif type_id == 2:
          A:		List[str]          =		'''layer_norm'''
     else:
          unused_weights.append(__lowercase	)
          return

     set_weights(__lowercase		,				__lowercase		,				__lowercase		,				F"""conv_layers.{layer_id}.{layer_type}.{weight_type}"""	)
def 					SCREAMING_SNAKE_CASE(   __lowercase		,				__lowercase		,				__lowercase		,				__lowercase	)			-> Optional[Any]:
     A:		Any          =		full_name.split('''pos_conv.'''	)[-1]
     A:		Any          =		name.split('''.'''	)
     A:		int          =		int(items[0]	)
     A:		Optional[int]          =		int(items[1]	)

     A:		Optional[Any]          =		name.split('''.'''	)[-1]
     if type_id != 0:
          unused_weights.append(__lowercase	)
          return
     else:
          A:		List[str]          =		'''conv'''

     set_weights(__lowercase		,				__lowercase		,				__lowercase		,				F"""layers.{layer_id}.{layer_type}.{weight_type}"""	)
@torch.no_grad()
def 					SCREAMING_SNAKE_CASE(   __lowercase		,				__lowercase		,				__lowercase=None		,				__lowercase=None		,				__lowercase=True	)			-> Optional[Any]:
     if config_path is not None:
          A:		Tuple          =		DataaVecAudioConfig.from_pretrained(__lowercase	)
     else:
          A:		Optional[Any]          =		DataaVecAudioConfig()

     if not is_finetuned:
          # Modify final_proj layer name
          A:		Union[str, Any]          =		DataaVecAudioModel(__lowercase	)
          A:		List[Any]          =		os.path.dirname(__lowercase	)

          A:		Union[str, Any]          =		torch.load(__lowercase	)
          A:		int          =		state_dict['''model'''].pop('''final_proj.0.weight'''	)
          A:		str          =		state_dict['''model'''].pop('''final_proj.0.bias'''	)
          A:		Any          =		os.path.join(__lowercase		,				'''converted.pt'''	)
          torch.save(__lowercase		,				__lowercase	)
     else:
          A:		Tuple          =		DataaVecAudioForCTC(__lowercase	)
          A:		Optional[int]          =		checkpoint_path

     def load_dataavec(__lowercase	):
          A     ,    A     ,    A:		List[Any]          =		fairseq.checkpoint_utils.load_model_ensemble_and_task([path]	)
          return model[0].eval()

     A:		Any          =		load_dataavec(__lowercase	)

     recursively_load_weights(__lowercase		,				__lowercase		,				not is_finetuned	)

     A:		Optional[int]          =		WavaVecaProcessor.from_pretrained('''facebook/wav2vec2-large-lv60'''	)

     A:		Optional[Any]          =		load_dataset('''patrickvonplaten/librispeech_asr_dummy'''		,				'''clean'''		,				split='''validation'''	)
     A:		Optional[int]          =		[x['''array'''] for x in ds[:4]['''audio''']]

     A:		Dict          =		processor(__lowercase		,				return_tensors='''pt'''		,				padding=__lowercase	)

     A:		str          =		inputs.input_values
     A:		str          =		inputs.attention_mask
     #    input_values = inputs.input_values[:, :-1]
     #    attention_mask = inputs.attention_mask[:, :-1]

     hf_wavavec.eval()
     model.eval()
     if is_finetuned:
          A:		Any          =		model(source=__lowercase		,				padding_mask=(1 - attention_mask)		,				mask=__lowercase		,				features_only=__lowercase	)[
              '''encoder_out'''
          ].transpose(0		,				1	)
          A:		int          =		hf_wavavec(__lowercase		,				attention_mask=__lowercase	)['''logits''']

          A:		str          =		torch.argmax(__lowercase		,				dim=-1	)
          A:		Any          =		processor.batch_decode(__lowercase	)

          print(F"""Expected Output: {ds[:4]['text']}, Pred: {output_string}"""	)
     else:
          A:		int          =		model(source=__lowercase		,				padding_mask=(1 - attention_mask)		,				mask=__lowercase		,				features_only=__lowercase	)[
              '''layer_results'''
          ][-1][0].transpose(0		,				1	)
          A:		List[Any]          =		hf_wavavec(__lowercase		,				attention_mask=__lowercase	)['''last_hidden_state''']

     print(our_output.shape		,				their_output.shape	)
     A:		List[Any]          =		torch.max(torch.abs(our_output - their_output	)	).item()
     print(F"""max_absolute_diff = {max_absolute_diff}"""	)  # ~ 1e-7
     A:		Optional[int]          =		torch.allclose(__lowercase		,				__lowercase		,				atol=1E-3	)
     print('''Do both models output the same tensors?'''		,				'''🔥''' if success else '''💩'''	)
     if not success:
          raise Exception('''Something went wRoNg'''	)

     hf_wavavec.save_pretrained(__lowercase	)

     if is_finetuned:
          processor.save_pretrained(__lowercase	)
     else:
          processor.feature_extractor.save_pretrained(__lowercase	)


if __name__ == "__main__":
     UpperCamelCase			     =					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('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
     parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
     parser.add_argument(
         '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not'''
     )
     UpperCamelCase			     =					parser.parse_args()
     convert_wavaveca_checkpoint(
         args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
     )












'''simple docstring'''


from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

UpperCamelCase			     =					TypeVar('''T''')
UpperCamelCase			     =					TypeVar('''U''')






class 						lowerCAmelCase_	(       Generic[T, U]							):







  '''simple docstring'''

  def __init__( self				:							Tuple					,  SCREAMING_SNAKE_CASE_				:							T | None					,  SCREAMING_SNAKE_CASE_				:							U | None	)			->		Any:







       '''simple docstring'''



       A:		Union[str, Any]          =		key
       A:		Union[str, Any]          =		val
       A:		int          =		0
       A:		DoubleLinkedListNode[T, U] | None          =		None
       A:		DoubleLinkedListNode[T, U] | None          =		None




  def __repr__( self				:							Any	)			->		str:







       '''simple docstring'''



       return "Node: key: {}, val: {}, freq: {}, has next: {}, has prev: {}".format(
           self.key					,  self.val					,  self.freq					,  self.next is not None					,  self.prev is not None	)






class 						lowerCAmelCase_	(       Generic[T, U]							):







  '''simple docstring'''

  def __init__( self				:							int	)			->		None:







       '''simple docstring'''



       A:		DoubleLinkedListNode[T, U]          =		DoubleLinkedListNode(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_	)
       A:		DoubleLinkedListNode[T, U]          =		DoubleLinkedListNode(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_	)
       A     ,    A:		Any          =		self.rear, self.head



  def __repr__( self				:							Optional[int]	)			->		str:







       '''simple docstring'''



       A:		int          =		['''DoubleLinkedList''']
       A:		Dict          =		self.head
       while node.next is not None:
            rep.append(str(SCREAMING_SNAKE_CASE_	)	)
            A:		int          =		node.next
       rep.append(str(self.rear	)	)
       return ",\n    ".join(SCREAMING_SNAKE_CASE_	)



  def 					_snake_case     ( self				:							Any					,  SCREAMING_SNAKE_CASE_				:							DoubleLinkedListNode[T, U]	)			->		None:







       '''simple docstring'''



       A:		Union[str, Any]          =		self.rear.prev

       # All nodes other than self.head are guaranteed to have non-None previous
       assert previous is not None

       A:		Optional[int]          =		node
       A:		int          =		previous
       A:		Dict          =		node
       A:		int          =		self.rear
       node.freq += 1
       self._position_node(SCREAMING_SNAKE_CASE_	)



  def 					_snake_case     ( self				:							int					,  SCREAMING_SNAKE_CASE_				:							DoubleLinkedListNode[T, U]	)			->		None:







       '''simple docstring'''



       while node.prev is not None and node.prev.freq > node.freq:
            # swap node with previous node
            A:		Any          =		node.prev

            A:		Optional[Any]          =		previous_node.prev
            A:		int          =		node.prev
            A:		int          =		previous_node
            A:		Optional[int]          =		node




  def 					_snake_case     ( self				:							Dict					,  SCREAMING_SNAKE_CASE_				:							DoubleLinkedListNode[T, U]	)			->		DoubleLinkedListNode[T, U] | None:







       '''simple docstring'''



       if node.prev is None or node.next is None:
            return None

       A:		List[Any]          =		node.next
       A:		Dict          =		node.prev
       A:		str          =		None
       A:		Union[str, Any]          =		None
       return node






class 						lowerCAmelCase_	(       Generic[T, U]							):







  '''simple docstring'''

  UpperCamelCase_			:      dict[Callable[[T], U], LFUCache[T, U]]										=				{}



  def __init__( self				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							int	)			->		int:







       '''simple docstring'''



       A:		DoubleLinkedList[T, U]          =		DoubleLinkedList()
       A:		Any          =		capacity
       A:		List[Any]          =		0
       A:		Dict          =		0
       A:		Dict          =		0
       A:		dict[T, DoubleLinkedListNode[T, U]]          =		{}



  def __repr__( self				:							Optional[int]	)			->		str:







       '''simple docstring'''



       return (
           f"""CacheInfo(hits={self.hits}, misses={self.miss}, """
           f"""capacity={self.capacity}, current_size={self.num_keys})"""
       )



  def __contains__( self				:							str					,  SCREAMING_SNAKE_CASE_				:							T	)			->		bool:







       '''simple docstring'''



       return key in self.cache



  def 					_snake_case     ( self				:							Dict					,  SCREAMING_SNAKE_CASE_				:							T	)			->		U | None:







       '''simple docstring'''



       if key in self.cache:
            self.hits += 1
            A:		DoubleLinkedListNode[T, U]          =		self.cache[key]
            A:		List[str]          =		self.list.remove(self.cache[key]	)
            assert node == value_node

            # node is guaranteed not None because it is in self.cache
            assert node is not None
            self.list.add(SCREAMING_SNAKE_CASE_	)
            return node.val
       self.miss += 1
       return None



  def 					_snake_case     ( self				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							T					,  SCREAMING_SNAKE_CASE_				:							U	)			->		None:







       '''simple docstring'''



       if key not in self.cache:
            if self.num_keys >= self.capacity:
                 # delete first node when over capacity
                 A:		List[Any]          =		self.list.head.next

                 # guaranteed to have a non-None first node when num_keys > 0
                 # explain to type checker via assertions
                 assert first_node is not None
                 assert first_node.key is not None
                 assert self.list.remove(SCREAMING_SNAKE_CASE_	) is not None
                 # first_node guaranteed to be in list

                 del self.cache[first_node.key]
                 self.num_keys -= 1
            A:		Tuple          =		DoubleLinkedListNode(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_	)
            self.list.add(self.cache[key]	)
            self.num_keys += 1

       else:
            A:		Optional[Any]          =		self.list.remove(self.cache[key]	)
            assert node is not None  # node guaranteed to be in list
            A:		List[str]          =		value
            self.list.add(SCREAMING_SNAKE_CASE_	)




  @classmethod
  def 					_snake_case     ( cls				:							type[LFUCache[T, U]]					,  SCREAMING_SNAKE_CASE_				:							int = 1_28	)			->		Callable[[Callable[[T], U]], Callable[..., U]]:







       '''simple docstring'''



       def cache_decorator_inner(SCREAMING_SNAKE_CASE_				:							Callable[[T], U]	) -> Callable[..., U]:
            def cache_decorator_wrapper(*SCREAMING_SNAKE_CASE_				:							T	) -> U:
                 if func not in cls.decorator_function_to_instance_map:
                      A:		Tuple          =		LFUCache(SCREAMING_SNAKE_CASE_	)

                 A:		List[Any]          =		cls.decorator_function_to_instance_map[func].get(args[0]	)
                 if result is None:
                      A:		List[str]          =		func(*SCREAMING_SNAKE_CASE_	)
                      cls.decorator_function_to_instance_map[func].put(args[0]					,  SCREAMING_SNAKE_CASE_	)
                 return result

            def cache_info() -> LFUCache[T, U]:
                 return cls.decorator_function_to_instance_map[func]

            setattr(SCREAMING_SNAKE_CASE_					,  '''cache_info'''					,  SCREAMING_SNAKE_CASE_	)  # noqa: B010

            return cache_decorator_wrapper

       return cache_decorator_inner


if __name__ == "__main__":
     import doctest

     doctest.testmod()






