





'''simple docstring'''



import math
import warnings
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch
from scipy import integrate

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin

@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->LMSDiscrete
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





			_lowerCAmelCase						=    42
			_lowerCAmelCase						=    None




def  lowercase__(		_UpperCamelCase  : Tuple ,   _UpperCamelCase  : str=0.999 ,   _UpperCamelCase  : Tuple="cosine" ,   )->   int:






					"""simple docstring"""

					if alpha_transform_type == "cosine":

										def alpha_bar_fn(_UpperCamelCase  : List[Any]				):
															return math.cos((t + 0.008) / 1.008 * math.pi / 2				) ** 2

					elif alpha_transform_type == "exp":

										def alpha_bar_fn(_UpperCamelCase  : Union[str, Any]				):
															return math.exp(t * -12.0				)

					else:
										raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}"				)

					_UpperCamelCase											=   []
					for i in range(_UpperCamelCase				):
										_UpperCamelCase											=   i / num_diffusion_timesteps
										_UpperCamelCase											=   (i + 1) / num_diffusion_timesteps
										betas.append(min(1 - alpha_bar_fn(_UpperCamelCase				) / alpha_bar_fn(_UpperCamelCase				) ,   _UpperCamelCase				)				)
					return torch.tensor(_UpperCamelCase ,   dtype=torch.floataa				)

class     A_ (  lowerCAmelCase_    ,			lowerCAmelCase_  ):

			'''simple docstring'''





			_lowerCAmelCase						=    [e.name for e in KarrasDiffusionSchedulers]
			_lowerCAmelCase						=    1




			@register_to_config
			def __init__(					self			,     A_ = 10_00			,     A_ = 0.0001			,     A_ = 0.02			,     A_ = "linear"			,     A_ = None			,     A_ = False			,     A_ = "epsilon"			,     A_ = "linspace"			,     A_ = 0			,     ):
								if trained_betas is not None:
													_UpperCamelCase											=   torch.tensor(A_			,     dtype=torch.floataa   )
								elif beta_schedule == "linear":
													_UpperCamelCase											=   torch.linspace(A_			,     A_			,     A_			,     dtype=torch.floataa   )
								elif beta_schedule == "scaled_linear":
													# this schedule is very specific to the latent diffusion model.
													_UpperCamelCase											=   (
													    torch.linspace(beta_start**0.5			,     beta_end**0.5			,     A_			,     dtype=torch.floataa   ) ** 2
													)
								elif beta_schedule == "squaredcos_cap_v2":
													# Glide cosine schedule
													_UpperCamelCase											=   betas_for_alpha_bar(A_   )
								else:
													raise NotImplementedError(F"{beta_schedule} does is not implemented for {self.__class__}"   )

								_UpperCamelCase											=   1.0 - self.betas
								_UpperCamelCase											=   torch.cumprod(self.alphas			,     dim=0   )

								_UpperCamelCase											=   np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5   )
								_UpperCamelCase											=   np.concatenate([sigmas[::-1], [0.0]]   ).astype(np.floataa   )
								_UpperCamelCase											=   torch.from_numpy(A_   )

								# setable values
								_UpperCamelCase											=   None
								_UpperCamelCase											=   use_karras_sigmas
								self.set_timesteps(A_			,     A_   )
								_UpperCamelCase											=   []
								_UpperCamelCase											=   False




			@property
			def       a	(					self   ):
								# standard deviation of the initial noise distribution
								if self.config.timestep_spacing in ["linspace", "trailing"]:
													return self.sigmas.max()

								return (self.sigmas.max() ** 2 + 1) ** 0.5




			def       a	(					self			,     A_			,     A_   ):
								if isinstance(A_			,     torch.Tensor   ):
													_UpperCamelCase											=   timestep.to(self.timesteps.device   )
								_UpperCamelCase											=   (self.timesteps == timestep).nonzero().item()
								_UpperCamelCase											=   self.sigmas[step_index]
								_UpperCamelCase											=   sample / ((sigma**2 + 1) ** 0.5)
								_UpperCamelCase											=   True
								return sample




			def       a	(					self			,     A_			,     A_			,     A_   ):

								def lms_derivative(A_   ):
													_UpperCamelCase											=   1.0
													for k in range(A_   ):
																		if current_order == k:
																							continue
																		prod *= (tau - self.sigmas[t - k]) / (self.sigmas[t - current_order] - self.sigmas[t - k])
													return prod

								_UpperCamelCase											=   integrate.quad(A_			,     self.sigmas[t]			,     self.sigmas[t + 1]			,     epsrel=1e-4   )[0]

								return integrated_coeff




			def       a	(					self			,     A_			,     A_ = None   ):
								_UpperCamelCase											=   num_inference_steps

								# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
								if self.config.timestep_spacing == "linspace":
													_UpperCamelCase											=   np.linspace(0			,     self.config.num_train_timesteps - 1			,     A_			,     dtype=A_   )[
													    ::-1
													].copy()
								elif self.config.timestep_spacing == "leading":
													_UpperCamelCase											=   self.config.num_train_timesteps // self.num_inference_steps
													# creates integer timesteps by multiplying by ratio
													# casting to int to avoid issues when num_inference_step is power of 3
													_UpperCamelCase											=   (np.arange(0			,     A_   ) * step_ratio).round()[::-1].copy().astype(A_   )
													timesteps += self.config.steps_offset
								elif self.config.timestep_spacing == "trailing":
													_UpperCamelCase											=   self.config.num_train_timesteps / self.num_inference_steps
													# creates integer timesteps by multiplying by ratio
													# casting to int to avoid issues when num_inference_step is power of 3
													_UpperCamelCase											=   (np.arange(self.config.num_train_timesteps			,     0			,     -step_ratio   )).round().copy().astype(A_   )
													timesteps -= 1
								else:
													raise ValueError(
													    F"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."   )

								_UpperCamelCase											=   np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5   )
								_UpperCamelCase											=   np.log(A_   )
								_UpperCamelCase											=   np.interp(A_			,     np.arange(0			,     len(A_   )   )			,     A_   )

								if self.use_karras_sigmas:
													_UpperCamelCase											=   self._convert_to_karras(in_sigmas=A_   )
													_UpperCamelCase											=   np.array([self._sigma_to_t(A_			,     A_   ) for sigma in sigmas]   )

								_UpperCamelCase											=   np.concatenate([sigmas, [0.0]]   ).astype(np.floataa   )

								_UpperCamelCase											=   torch.from_numpy(A_   ).to(device=A_   )
								if str(A_   ).startswith("mps"   ):
													# mps does not support float64
													_UpperCamelCase											=   torch.from_numpy(A_   ).to(A_			,     dtype=torch.floataa   )
								else:
													_UpperCamelCase											=   torch.from_numpy(A_   ).to(device=A_   )

								_UpperCamelCase											=   []




			def       a	(					self			,     A_			,     A_   ):
								# get log sigma
								_UpperCamelCase											=   np.log(A_   )

								# get distribution
								_UpperCamelCase											=   log_sigma - log_sigmas[:, np.newaxis]

								# get sigmas range
								_UpperCamelCase											=   np.cumsum((dists >= 0)			,     axis=0   ).argmax(axis=0   ).clip(max=log_sigmas.shape[0] - 2   )
								_UpperCamelCase											=   low_idx + 1

								_UpperCamelCase											=   log_sigmas[low_idx]
								_UpperCamelCase											=   log_sigmas[high_idx]

								# interpolate sigmas
								_UpperCamelCase											=   (low - log_sigma) / (low - high)
								_UpperCamelCase											=   np.clip(A_			,     0			,     1   )

								# transform interpolation to time range
								_UpperCamelCase											=   (1 - w) * low_idx + w * high_idx
								_UpperCamelCase											=   t.reshape(sigma.shape   )
								return t




			def       a	(					self			,     A_   ):
								_UpperCamelCase											=   in_sigmas[-1].item()
								_UpperCamelCase											=   in_sigmas[0].item()

								_UpperCamelCase											=   7.0  # 7.0 is the value used in the paper
								_UpperCamelCase											=   np.linspace(0			,     1			,     self.num_inference_steps   )
								_UpperCamelCase											=   sigma_min ** (1 / rho)
								_UpperCamelCase											=   sigma_max ** (1 / rho)
								_UpperCamelCase											=   (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
								return sigmas




			def       a	(					self			,     A_			,     A_			,     A_			,     A_ = 4			,     A_ = True			,     ):
								if not self.is_scale_input_called:
													warnings.warn(
													    "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
													    "See `StableDiffusionPipeline` for a usage example."   )

								if isinstance(A_			,     torch.Tensor   ):
													_UpperCamelCase											=   timestep.to(self.timesteps.device   )
								_UpperCamelCase											=   (self.timesteps == timestep).nonzero().item()
								_UpperCamelCase											=   self.sigmas[step_index]

								# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
								if self.config.prediction_type == "epsilon":
													_UpperCamelCase											=   sample - sigma * model_output
								elif self.config.prediction_type == "v_prediction":
													# * c_out + input * c_skip
													_UpperCamelCase											=   model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
								elif self.config.prediction_type == "sample":
													_UpperCamelCase											=   model_output
								else:
													raise ValueError(
													    F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"   )

								# 2. Convert to an ODE derivative
								_UpperCamelCase											=   (sample - pred_original_sample) / sigma
								self.derivatives.append(A_   )
								if len(self.derivatives   ) > order:
													self.derivatives.pop(0   )

								# 3. Compute linear multistep coefficients
								_UpperCamelCase											=   min(step_index + 1			,     A_   )
								_UpperCamelCase											=   [self.get_lms_coefficient(A_			,     A_			,     A_   ) for curr_order in range(A_   )]

								# 4. Compute previous sample based on the derivatives path
								_UpperCamelCase											=   sample + sum(
								    coeff * derivative for coeff, derivative in zip(A_			,     reversed(self.derivatives   )   )   )

								if not return_dict:
													return (prev_sample,)

								return LMSDiscreteSchedulerOutput(prev_sample=A_			,     pred_original_sample=A_   )




			def       a	(					self			,     A_			,     A_			,     A_			,     ):
								# Make sure sigmas and timesteps have the same device and dtype as original_samples
								_UpperCamelCase											=   self.sigmas.to(device=original_samples.device			,     dtype=original_samples.dtype   )
								if original_samples.device.type == "mps" and torch.is_floating_point(A_   ):
													# mps does not support float64
													_UpperCamelCase											=   self.timesteps.to(original_samples.device			,     dtype=torch.floataa   )
													_UpperCamelCase											=   timesteps.to(original_samples.device			,     dtype=torch.floataa   )
								else:
													_UpperCamelCase											=   self.timesteps.to(original_samples.device   )
													_UpperCamelCase											=   timesteps.to(original_samples.device   )

								_UpperCamelCase											=   [(schedule_timesteps == t).nonzero().item() for t in timesteps]

								_UpperCamelCase											=   sigmas[step_indices].flatten()
								while len(sigma.shape   ) < len(original_samples.shape   ):
													_UpperCamelCase											=   sigma.unsqueeze(-1   )

								_UpperCamelCase											=   original_samples + noise * sigma
								return noisy_samples




			def __len__(					self   ):
								return self.config.num_train_timesteps










'''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()
snake_case_   :  Optional[Any]								=      logging.get_logger(__name__)

snake_case_   :  Optional[Any]								=      {
    '''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''',
}
snake_case_   :  Optional[Any]								=      [
    '''lm_head''',
]



def  lowercase__(		_UpperCamelCase  : List[Any] ,   _UpperCamelCase  : Optional[Any] ,   _UpperCamelCase  : Tuple ,   _UpperCamelCase  : Tuple ,   _UpperCamelCase  : Optional[Any]				)->   Tuple:






					"""simple docstring"""

					for attribute in key.split("."				):
										_UpperCamelCase											=   getattr(_UpperCamelCase ,   _UpperCamelCase				)

					if weight_type is not None:
										_UpperCamelCase											=   getattr(_UpperCamelCase ,   _UpperCamelCase				).shape
					else:
										_UpperCamelCase											=   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":
										_UpperCamelCase											=   value
					elif weight_type == "weight_g":
										_UpperCamelCase											=   value
					elif weight_type == "weight_v":
										_UpperCamelCase											=   value
					elif weight_type == "bias":
										_UpperCamelCase											=   value
					else:
										_UpperCamelCase											=   value

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



def  lowercase__(		_UpperCamelCase  : Tuple ,   _UpperCamelCase  : Optional[Any] ,   _UpperCamelCase  : List[str]				)->   List[str]:






					"""simple docstring"""

					_UpperCamelCase											=   []
					_UpperCamelCase											=   fairseq_model.state_dict()

					if not is_headless:
										_UpperCamelCase											=   hf_model.dataavec_audio.feature_extractor
										_UpperCamelCase											=   hf_model.dataavec_audio.encoder.pos_conv_embed

					else:
										_UpperCamelCase											=   hf_model.feature_extractor
										_UpperCamelCase											=   hf_model.encoder.pos_conv_embed

					for name, value in fairseq_dict.items():
										_UpperCamelCase											=   False
										if "conv_layers" in name:
															load_conv_layer(
															    _UpperCamelCase ,   _UpperCamelCase ,   _UpperCamelCase ,   _UpperCamelCase ,   )
															_UpperCamelCase											=   True
										elif "pos_conv" in name:
															load_pos_conv_layer(
															    _UpperCamelCase ,   _UpperCamelCase ,   _UpperCamelCase ,   _UpperCamelCase ,   )
															_UpperCamelCase											=   True
										else:
															for key, mapped_key in MAPPING.items():
																				if not is_headless:
																									_UpperCamelCase											=   "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]:
																									_UpperCamelCase											=   True
																									if "*" in mapped_key:
																														_UpperCamelCase											=   name.split(_UpperCamelCase				)[0].split("."				)[-2]
																														_UpperCamelCase											=   mapped_key.replace("*" ,   _UpperCamelCase				)
																									if "weight_g" in name:
																														_UpperCamelCase											=   "weight_g"
																									elif "weight_v" in name:
																														_UpperCamelCase											=   "weight_v"
																									elif "bias" in name:
																														_UpperCamelCase											=   "bias"
																									elif "weight" in name:
																														# TODO: don't match quantizer.weight_proj
																														_UpperCamelCase											=   "weight"
																									else:
																														_UpperCamelCase											=   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  lowercase__(		_UpperCamelCase  : List[Any] ,   _UpperCamelCase  : Tuple				)->   int:






					"""simple docstring"""

					_UpperCamelCase											=   path.split("."				)
					return reduce(_UpperCamelCase ,   _UpperCamelCase ,   _UpperCamelCase				)



def  lowercase__(		_UpperCamelCase  : str ,   _UpperCamelCase  : List[Any] ,   _UpperCamelCase  : Dict ,   _UpperCamelCase  : List[str]				)->   List[str]:






					"""simple docstring"""

					_UpperCamelCase											=   access_by_string(_UpperCamelCase ,   _UpperCamelCase				)
					_UpperCamelCase											=   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."				)
					_UpperCamelCase											=   fsq_value
					logger.info(f"{full_name} was correctly initialized from {hf_weight_path}."				)



def  lowercase__(		_UpperCamelCase  : Tuple ,   _UpperCamelCase  : Union[str, Any] ,   _UpperCamelCase  : int ,   _UpperCamelCase  : str				)->   Dict:






					"""simple docstring"""

					_UpperCamelCase											=   full_name.split("conv_layers."				)[-1]
					_UpperCamelCase											=   name.split("."				)
					_UpperCamelCase											=   int(items[0]				)
					_UpperCamelCase											=   int(items[1]				)

					_UpperCamelCase											=   name.split("."				)[-1]
					if type_id == 0:
										_UpperCamelCase											=   "conv"
					elif type_id == 2:
										_UpperCamelCase											=   "layer_norm"
					else:
										unused_weights.append(_UpperCamelCase				)
										return

					set_weights(_UpperCamelCase ,   _UpperCamelCase ,   _UpperCamelCase ,   f"conv_layers.{layer_id}.{layer_type}.{weight_type}"				)



def  lowercase__(		_UpperCamelCase  : Union[str, Any] ,   _UpperCamelCase  : List[Any] ,   _UpperCamelCase  : Tuple ,   _UpperCamelCase  : int				)->   Dict:






					"""simple docstring"""

					_UpperCamelCase											=   full_name.split("pos_conv."				)[-1]
					_UpperCamelCase											=   name.split("."				)
					_UpperCamelCase											=   int(items[0]				)
					_UpperCamelCase											=   int(items[1]				)

					_UpperCamelCase											=   name.split("."				)[-1]
					if type_id != 0:
										unused_weights.append(_UpperCamelCase				)
										return
					else:
										_UpperCamelCase											=   "conv"

					set_weights(_UpperCamelCase ,   _UpperCamelCase ,   _UpperCamelCase ,   f"layers.{layer_id}.{layer_type}.{weight_type}"				)



@torch.no_grad()
def  lowercase__(		_UpperCamelCase  : List[Any] ,   _UpperCamelCase  : Tuple ,   _UpperCamelCase  : Optional[Any]=None ,   _UpperCamelCase  : List[Any]=None ,   _UpperCamelCase  : Optional[Any]=True				)->   Optional[int]:






					"""simple docstring"""

					if config_path is not None:
										_UpperCamelCase											=   DataaVecAudioConfig.from_pretrained(_UpperCamelCase				)
					else:
										_UpperCamelCase											=   DataaVecAudioConfig()

					if not is_finetuned:
										# Modify final_proj layer name
										_UpperCamelCase											=   DataaVecAudioModel(_UpperCamelCase				)
										_UpperCamelCase											=   os.path.dirname(_UpperCamelCase				)

										_UpperCamelCase											=   torch.load(_UpperCamelCase				)
										_UpperCamelCase											=   state_dict["model"].pop("final_proj.0.weight"				)
										_UpperCamelCase											=   state_dict["model"].pop("final_proj.0.bias"				)
										_UpperCamelCase											=   os.path.join(_UpperCamelCase ,   "converted.pt"				)
										torch.save(_UpperCamelCase ,   _UpperCamelCase				)
					else:
										_UpperCamelCase											=   DataaVecAudioForCTC(_UpperCamelCase				)
										_UpperCamelCase											=   checkpoint_path

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

					_UpperCamelCase											=   load_dataavec(_UpperCamelCase				)

					recursively_load_weights(_UpperCamelCase ,   _UpperCamelCase ,   not is_finetuned				)

					_UpperCamelCase											=   WavaVecaProcessor.from_pretrained("facebook/wav2vec2-large-lv60"				)

					_UpperCamelCase											=   load_dataset("patrickvonplaten/librispeech_asr_dummy" ,   "clean" ,   split="validation"				)
					_UpperCamelCase											=   [x["array"] for x in ds[:4]["audio"]]

					_UpperCamelCase											=   processor(_UpperCamelCase ,   return_tensors="pt" ,   padding=_UpperCamelCase				)

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

					hf_wavavec.eval()
					model.eval()
					if is_finetuned:
										_UpperCamelCase											=   model(source=_UpperCamelCase ,   padding_mask=(1 - attention_mask) ,   mask=_UpperCamelCase ,   features_only=_UpperCamelCase				)[
										    "encoder_out"
										].transpose(0 ,   1				)
										_UpperCamelCase											=   hf_wavavec(_UpperCamelCase ,   attention_mask=_UpperCamelCase				)["logits"]

										_UpperCamelCase											=   torch.argmax(_UpperCamelCase ,   dim=-1				)
										_UpperCamelCase											=   processor.batch_decode(_UpperCamelCase				)

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

					print(our_output.shape ,   their_output.shape				)
					_UpperCamelCase											=   torch.max(torch.abs(our_output - their_output				)				).item()
					print(f"max_absolute_diff = {max_absolute_diff}"				)  # ~ 1e-7
					_UpperCamelCase											=   torch.allclose(_UpperCamelCase ,   _UpperCamelCase ,   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(_UpperCamelCase				)

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


if __name__ == "__main__":
			snake_case_   :  int								=      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'''
			)
			snake_case_   :  Any								=      parser.parse_args()
			convert_wavaveca_checkpoint(
			    args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
			)



