






import importlib
import importlib.metadata
import os
import warnings
from distutils.util import strtobool
from functools import lru_cache

import torch
from packaging import version
from packaging.version import parse

from .environment import parse_flag_from_env
from .versions import compare_versions, is_torch_version


try:
					import torch_xla.core.xla_model as xm  # noqa: F401

					snake_case_   :	str							      =True
except ImportError:
					snake_case_   :	List[Any]							      =False


# Cache this result has it's a C FFI call which can be pretty time-consuming
snake_case_   :	Any							      =torch.distributed.is_available()



def      UpperCAmelCase						( lowerCAmelCase__	):


		'''simple docstring'''

		__A    =							importlib.util.find_spec(__lowercase	) is not None
		if package_exists:
				try:
						__A    =							importlib.metadata.metadata(__lowercase	)
						return True
				except importlib.metadata.PackageNotFoundError:
						return False



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _torch_distributed_available



def      UpperCAmelCase						( ):


		'''simple docstring'''

		try:
				pass
		except ImportError:
				print(
				    "Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not"
				    " detected. If you see \"ValueError: Invalid backend: \'ccl\'\" error, please install Intel(R) oneCCL"
				    " Bindings for PyTorch*."	)
		return (
		    importlib.util.find_spec("torch_ccl"	) is not None
		    or importlib.util.find_spec("oneccl_bindings_for_pytorch"	) is not None
		)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return importlib.metadata.version("oneccl_bind_pt"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("transformer_engine"	)



@lru_cache
def      UpperCAmelCase						( lowerCAmelCase__=True	):


		'''simple docstring'''

		if torch.cuda.is_available():
				return False
		if _tpu_available and check_device:
				try:
						# Will raise a RuntimeError if no XLA configuration is found
						__A    =							xm.xla_device()
						return True
				except RuntimeError:
						return False
		return _tpu_available



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("deepspeed"	)



def      UpperCAmelCase						( lowerCAmelCase__=False	):


		'''simple docstring'''

		if is_tpu_available():
				return not ignore_tpu
		if torch.cuda.is_available():
				return torch.cuda.is_bfaa_supported()
		if is_npu_available():
				return False
		return True



def      UpperCAmelCase						( ):


		'''simple docstring'''

		__A    =							_is_package_available("bitsandbytes"	)
		if package_exists:
				__A    =							version.parse(importlib.metadata.version("bitsandbytes"	)	)
				return compare_versions(__lowercase					,     ">="					,     "0.39.0"	)
		return False



def      UpperCAmelCase						( ):


		'''simple docstring'''

		__A    =							_is_package_available("bitsandbytes"	)
		if package_exists:
				__A    =							version.parse(importlib.metadata.version("bitsandbytes"	)	)
				return compare_versions(__lowercase					,     ">="					,     "0.37.2"	)
		return False



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("bitsandbytes"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		if strtobool(os.environ.get("ACCELERATE_USE_MEGATRON_LM"					,     "False"	)	) == 1:
				__A    =							importlib.util.find_spec("megatron"	) is not None
				if package_exists:
						try:
								__A    =							parse(importlib.metadata.version("megatron-lm"	)	)
								return compare_versions(__lowercase					,     ">="					,     "2.2.0"	)
						except Exception as e:
								warnings.warn(F"""Parse Megatron version failed. Exception:{e}"""	)
								return False



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("safetensors"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("transformers"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("datasets"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("aim"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("tensorboard"	) or _is_package_available("tensorboardX"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("wandb"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("comet_ml"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("boto3"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		if _is_package_available("rich"	):
				if "ACCELERATE_DISABLE_RICH" in os.environ:
						warnings.warn(
						    "`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`."	)
						return not parse_flag_from_env("ACCELERATE_DISABLE_RICH"					,     __lowercase	)
				return parse_flag_from_env("ACCELERATE_ENABLE_RICH"					,     __lowercase	)
		return False



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("sagemaker"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("tqdm"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return _is_package_available("mlflow"	)



def      UpperCAmelCase						( ):


		'''simple docstring'''

		return is_torch_version(">="					,     "1.12"	) and torch.backends.mps.is_available() and torch.backends.mps.is_built()



def      UpperCAmelCase						( ):


		'''simple docstring'''

		def get_major_and_minor_from_version(lowerCAmelCase__	):
				return str(version.parse(__lowercase	).major	) + "." + str(version.parse(__lowercase	).minor	)

		__A    =							importlib.metadata.version("torch"	)
		if importlib.util.find_spec("intel_extension_for_pytorch"	) is None:
				return False
		__A    =							'''N/A'''
		try:
				__A    =							importlib.metadata.version("intel_extension_for_pytorch"	)
		except importlib.metadata.PackageNotFoundError:
				return False
		__A    =							get_major_and_minor_from_version(_torch_version	)
		__A    =							get_major_and_minor_from_version(_ipex_version	)
		if torch_major_and_minor != ipex_major_and_minor:
				warnings.warn(
				    F"""Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"""
				    F""" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."""	)
				return False
		return True



@lru_cache
def      UpperCAmelCase						( lowerCAmelCase__=False	):


		'''simple docstring'''

		if importlib.util.find_spec("torch"	) is None or importlib.util.find_spec("torch_npu"	) is None:
				return False

		import torch
		import torch_npu  # noqa: F401

		if check_device:
				try:
						# Will raise a RuntimeError if no NPU is found
						__A    =							torch.npu.device_count()
						return torch.npu.is_available()
				except RuntimeError:
						return False
		return hasattr(__lowercase					,     "npu"	) and torch.npu.is_available()





@lru_cache
def      UpperCAmelCase						( lowerCAmelCase__=False	):


		'''simple docstring'''

		if not parse_flag_from_env("ACCELERATE_USE_XPU"					,     default=__lowercase	):
				return False
		if is_ipex_available():
				import torch

				if is_torch_version("<="					,     "1.12"	):
						return False
		else:
				return False

		import intel_extension_for_pytorch  # noqa: F401

		if check_device:
				try:
						# Will raise a RuntimeError if no XPU  is found
						__A    =							torch.xpu.device_count()
						return torch.xpu.is_available()
				except RuntimeError:
						return False
		return hasattr(__lowercase					,     "xpu"	) and torch.xpu.is_available()







'''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
     )






