


import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


A      :    List[str]		=					re.compile(r"\b(a|an|the)\b", re.UNICODE)

A      :    int		=					None

def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				Any    =  argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0."						)
      parser.add_argument("data_file"    ,					metavar="data.json"    ,					help="Input data JSON file."						)
      parser.add_argument("pred_file"    ,					metavar="pred.json"    ,					help="Model predictions."						)
      parser.add_argument(
          "--out-file"    ,					"-o"    ,					metavar="eval.json"    ,					help="Write accuracy metrics to file (default is stdout)."						)
      parser.add_argument(
          "--na-prob-file"    ,					"-n"    ,					metavar="na_prob.json"    ,					help="Model estimates of probability of no answer."						)
      parser.add_argument(
          "--na-prob-thresh"    ,					"-t"    ,					type=_lowerCAmelCase    ,					default=1.0    ,					help="Predict \"\" if no-answer probability exceeds this (default = 1.0)."    ,					)
      parser.add_argument(
          "--out-image-dir"    ,					"-p"    ,					metavar="out_images"    ,					default=_lowerCAmelCase    ,					help="Save precision-recall curves to directory."						)
      parser.add_argument("--verbose"    ,					"-v"    ,					action="store_true"						)
      if len(sys.argv						) == 1:
            parser.print_help()
            sys.exit(1						)
      return parser.parse_args()

def       lowercase_		(		_A			:    Any						):

      """simple docstring"""




      lowerCamelCase__		:				Any    =  {}
      for article in dataset:
            for p in article["paragraphs"]:
                  for qa in p["qas"]:
                        lowerCamelCase__		:				List[str]    =  bool(qa["answers"]["text"]						)
      return qid_to_has_ans

def       lowercase_		(		_A			:    Any						):

      """simple docstring"""




      def remove_articles(_A			:    str						):
            return ARTICLES_REGEX.sub(" "    ,					_lowerCAmelCase						)

      def white_space_fix(_A			:    Dict						):
            return " ".join(text.split()						)

      def remove_punc(_A			:    Optional[Any]						):
            lowerCamelCase__		:				Optional[int]    =  set(string.punctuation						)
            return "".join(ch for ch in text if ch not in exclude						)

      def lower(_A			:    int						):
            return text.lower()

      return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase						)						)						)						)

def       lowercase_		(		_A			:    Union[str, Any]						):

      """simple docstring"""




      if not s:
            return []
      return normalize_answer(_lowerCAmelCase						).split()

def       lowercase_		(		_A			:    Optional[Any]    ,					_A			:    List[Any]						):

      """simple docstring"""




      return int(normalize_answer(_lowerCAmelCase						) == normalize_answer(_lowerCAmelCase						)						)

def       lowercase_		(		_A			:    str    ,					_A			:    int						):

      """simple docstring"""




      lowerCamelCase__		:				Union[str, Any]    =  get_tokens(_lowerCAmelCase						)
      lowerCamelCase__		:				Optional[Any]    =  get_tokens(_lowerCAmelCase						)
      lowerCamelCase__		:				Optional[Any]    =  collections.Counter(_lowerCAmelCase						) & collections.Counter(_lowerCAmelCase						)
      lowerCamelCase__		:				int    =  sum(common.values()						)
      if len(_lowerCAmelCase						) == 0 or len(_lowerCAmelCase						) == 0:
            # If either is no-answer, then F1 is 1 if they agree, 0 otherwise
            return int(gold_toks == pred_toks						)
      if num_same == 0:
            return 0
      lowerCamelCase__		:				List[Any]    =  1.0 * num_same / len(_lowerCAmelCase						)
      lowerCamelCase__		:				Any    =  1.0 * num_same / len(_lowerCAmelCase						)
      lowerCamelCase__		:				List[str]    =  (2 * precision * recall) / (precision + recall)
      return fa

def       lowercase_		(		_A			:    Union[str, Any]    ,					_A			:    Optional[int]						):

      """simple docstring"""




      lowerCamelCase__		:				Optional[Any]    =  {}
      lowerCamelCase__		:				Any    =  {}
      for article in dataset:
            for p in article["paragraphs"]:
                  for qa in p["qas"]:
                        lowerCamelCase__		:				Optional[int]    =  qa["""id"""]
                        lowerCamelCase__		:				Optional[Any]    =  [t for t in qa["""answers"""]["""text"""] if normalize_answer(_lowerCAmelCase						)]
                        if not gold_answers:
                              # For unanswerable questions, only correct answer is empty string
                              lowerCamelCase__		:				Optional[int]    =  [""""""]
                        if qid not in preds:
                              print(F"Missing prediction for {qid}"						)
                              continue
                        lowerCamelCase__		:				Tuple    =  preds[qid]
                        # Take max over all gold answers
                        lowerCamelCase__		:				str    =  max(compute_exact(_lowerCAmelCase    ,					_lowerCAmelCase						) for a in gold_answers						)
                        lowerCamelCase__		:				Any    =  max(compute_fa(_lowerCAmelCase    ,					_lowerCAmelCase						) for a in gold_answers						)
      return exact_scores, fa_scores

def       lowercase_		(		_A			:    List[Any]    ,					_A			:    List[str]    ,					_A			:    int    ,					_A			:    List[str]						):

      """simple docstring"""




      lowerCamelCase__		:				Optional[int]    =  {}
      for qid, s in scores.items():
            lowerCamelCase__		:				Optional[Any]    =  na_probs[qid] > na_prob_thresh
            if pred_na:
                  lowerCamelCase__		:				Optional[int]    =  float(not qid_to_has_ans[qid]						)
            else:
                  lowerCamelCase__		:				Union[str, Any]    =  s
      return new_scores

def       lowercase_		(		_A			:    str    ,					_A			:    Any    ,					_A			:    Optional[int]=None						):

      """simple docstring"""




      if not qid_list:
            lowerCamelCase__		:				str    =  len(_lowerCAmelCase						)
            return collections.OrderedDict(
                [
                    ("exact", 100.0 * sum(exact_scores.values()						) / total),
                    ("f1", 100.0 * sum(fa_scores.values()						) / total),
                    ("total", total),
                ]						)
      else:
            lowerCamelCase__		:				int    =  len(_lowerCAmelCase						)
            return collections.OrderedDict(
                [
                    ("exact", 100.0 * sum(exact_scores[k] for k in qid_list						) / total),
                    ("f1", 100.0 * sum(fa_scores[k] for k in qid_list						) / total),
                    ("total", total),
                ]						)

def       lowercase_		(		_A			:    Tuple    ,					_A			:    str    ,					_A			:    List[Any]						):

      """simple docstring"""




      for k in new_eval:
            lowerCamelCase__		:				str    =  new_eval[k]

def       lowercase_		(		_A			:    Union[str, Any]    ,					_A			:    Optional[Any]    ,					_A			:    int    ,					_A			:    Optional[int]						):

      """simple docstring"""




      plt.step(_lowerCAmelCase    ,					_lowerCAmelCase    ,					color="b"    ,					alpha=0.2    ,					where="post"						)
      plt.fill_between(_lowerCAmelCase    ,					_lowerCAmelCase    ,					step="post"    ,					alpha=0.2    ,					color="b"						)
      plt.xlabel("Recall"						)
      plt.ylabel("Precision"						)
      plt.xlim([0.0, 1.05]						)
      plt.ylim([0.0, 1.05]						)
      plt.title(_lowerCAmelCase						)
      plt.savefig(_lowerCAmelCase						)
      plt.clf()

def       lowercase_		(		_A			:    List[str]    ,					_A			:    Dict    ,					_A			:    Optional[Any]    ,					_A			:    Union[str, Any]    ,					_A			:    List[Any]=None    ,					_A			:    Optional[int]=None						):

      """simple docstring"""




      lowerCamelCase__		:				Optional[int]    =  sorted(_lowerCAmelCase    ,					key=lambda _A						: na_probs[k]						)
      lowerCamelCase__		:				str    =  0.0
      lowerCamelCase__		:				Dict    =  1.0
      lowerCamelCase__		:				List[str]    =  0.0
      lowerCamelCase__		:				Dict    =  [1.0]
      lowerCamelCase__		:				int    =  [0.0]
      lowerCamelCase__		:				str    =  0.0
      for i, qid in enumerate(_lowerCAmelCase						):
            if qid_to_has_ans[qid]:
                  true_pos += scores[qid]
            lowerCamelCase__		:				Dict    =  true_pos / float(i + 1						)
            lowerCamelCase__		:				Union[str, Any]    =  true_pos / float(_lowerCAmelCase						)
            if i == len(_lowerCAmelCase						) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
                  # i.e., if we can put a threshold after this point
                  avg_prec += cur_p * (cur_r - recalls[-1])
                  precisions.append(_lowerCAmelCase						)
                  recalls.append(_lowerCAmelCase						)
      if out_image:
            plot_pr_curve(_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase						)
      return {"ap": 100.0 * avg_prec}

def       lowercase_		(		_A			:    int    ,					_A			:    str    ,					_A			:    Optional[int]    ,					_A			:    List[Any]    ,					_A			:    Any    ,					_A			:    Any						):

      """simple docstring"""




      if out_image_dir and not os.path.exists(_lowerCAmelCase						):
            os.makedirs(_lowerCAmelCase						)
      lowerCamelCase__		:				Optional[Any]    =  sum(1 for v in qid_to_has_ans.values() if v						)
      if num_true_pos == 0:
            return
      lowerCamelCase__		:				Any    =  make_precision_recall_eval(
          _lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					out_image=os.path.join(_lowerCAmelCase    ,					"pr_exact.png"						)    ,					title="Precision-Recall curve for Exact Match score"    ,					)
      lowerCamelCase__		:				Optional[Any]    =  make_precision_recall_eval(
          _lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					out_image=os.path.join(_lowerCAmelCase    ,					"pr_f1.png"						)    ,					title="Precision-Recall curve for F1 score"    ,					)
      lowerCamelCase__		:				Any    =  {k: float(_lowerCAmelCase						) for k, v in qid_to_has_ans.items()}
      lowerCamelCase__		:				Union[str, Any]    =  make_precision_recall_eval(
          _lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					out_image=os.path.join(_lowerCAmelCase    ,					"pr_oracle.png"						)    ,					title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"    ,					)
      merge_eval(_lowerCAmelCase    ,					_lowerCAmelCase    ,					"pr_exact"						)
      merge_eval(_lowerCAmelCase    ,					_lowerCAmelCase    ,					"pr_f1"						)
      merge_eval(_lowerCAmelCase    ,					_lowerCAmelCase    ,					"pr_oracle"						)

def       lowercase_		(		_A			:    Tuple    ,					_A			:    Union[str, Any]    ,					_A			:    Any    ,					_A			:    Optional[Any]						):

      """simple docstring"""




      if not qid_list:
            return
      lowerCamelCase__		:				Optional[Any]    =  [na_probs[k] for k in qid_list]
      lowerCamelCase__		:				Union[str, Any]    =  np.ones_like(_lowerCAmelCase						) / float(len(_lowerCAmelCase						)						)
      plt.hist(_lowerCAmelCase    ,					weights=_lowerCAmelCase    ,					bins=20    ,					range=(0.0, 1.0)						)
      plt.xlabel("Model probability of no-answer"						)
      plt.ylabel("Proportion of dataset"						)
      plt.title(F"Histogram of no-answer probability: {name}"						)
      plt.savefig(os.path.join(_lowerCAmelCase    ,					F"na_prob_hist_{name}.png"						)						)
      plt.clf()

def       lowercase_		(		_A			:    Optional[Any]    ,					_A			:    List[Any]    ,					_A			:    Dict    ,					_A			:    List[Any]						):

      """simple docstring"""




      lowerCamelCase__		:				List[str]    =  sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]						)
      lowerCamelCase__		:				Union[str, Any]    =  num_no_ans
      lowerCamelCase__		:				Optional[int]    =  cur_score
      lowerCamelCase__		:				Optional[Any]    =  0.0
      lowerCamelCase__		:				Optional[int]    =  sorted(_lowerCAmelCase    ,					key=lambda _A						: na_probs[k]						)
      for i, qid in enumerate(_lowerCAmelCase						):
            if qid not in scores:
                  continue
            if qid_to_has_ans[qid]:
                  lowerCamelCase__		:				List[str]    =  scores[qid]
            else:
                  if preds[qid]:
                        lowerCamelCase__		:				Tuple    =  -1
                  else:
                        lowerCamelCase__		:				List[Any]    =  0
            cur_score += diff
            if cur_score > best_score:
                  lowerCamelCase__		:				Optional[Any]    =  cur_score
                  lowerCamelCase__		:				Union[str, Any]    =  na_probs[qid]
      return 100.0 * best_score / len(_lowerCAmelCase						), best_thresh

def       lowercase_		(		_A			:    List[Any]    ,					_A			:    Optional[Any]    ,					_A			:    Optional[int]    ,					_A			:    Any    ,					_A			:    List[str]    ,					_A			:    Dict						):

      """simple docstring"""




      lowerCamelCase__		:				List[str]    =  find_best_thresh(_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase						)
      lowerCamelCase__		:				int    =  find_best_thresh(_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase						)
      lowerCamelCase__		:				List[Any]    =  best_exact
      lowerCamelCase__		:				Dict    =  exact_thresh
      lowerCamelCase__		:				List[Any]    =  best_fa
      lowerCamelCase__		:				Dict    =  fa_thresh

def       lowercase_		(		):

      """simple docstring"""




      with open(OPTS.data_file						) as f:
            lowerCamelCase__		:				Union[str, Any]    =  json.load(_lowerCAmelCase						)
            lowerCamelCase__		:				Dict    =  dataset_json["""data"""]
      with open(OPTS.pred_file						) as f:
            lowerCamelCase__		:				int    =  json.load(_lowerCAmelCase						)
      if OPTS.na_prob_file:
            with open(OPTS.na_prob_file						) as f:
                  lowerCamelCase__		:				Tuple    =  json.load(_lowerCAmelCase						)
      else:
            lowerCamelCase__		:				List[Any]    =  {k: 0.0 for k in preds}
      lowerCamelCase__		:				List[Any]    =  make_qid_to_has_ans(_lowerCAmelCase						)  # maps qid to True/False
      lowerCamelCase__		:				Optional[int]    =  [k for k, v in qid_to_has_ans.items() if v]
      lowerCamelCase__		:				str    =  [k for k, v in qid_to_has_ans.items() if not v]
      lowerCamelCase__		:				int    =  get_raw_scores(_lowerCAmelCase    ,					_lowerCAmelCase						)
      lowerCamelCase__		:				Dict    =  apply_no_ans_threshold(_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					OPTS.na_prob_thresh						)
      lowerCamelCase__		:				Optional[Any]    =  apply_no_ans_threshold(_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					OPTS.na_prob_thresh						)
      lowerCamelCase__		:				List[Any]    =  make_eval_dict(_lowerCAmelCase    ,					_lowerCAmelCase						)
      if has_ans_qids:
            lowerCamelCase__		:				Optional[Any]    =  make_eval_dict(_lowerCAmelCase    ,					_lowerCAmelCase    ,					qid_list=_lowerCAmelCase						)
            merge_eval(_lowerCAmelCase    ,					_lowerCAmelCase    ,					"HasAns"						)
      if no_ans_qids:
            lowerCamelCase__		:				str    =  make_eval_dict(_lowerCAmelCase    ,					_lowerCAmelCase    ,					qid_list=_lowerCAmelCase						)
            merge_eval(_lowerCAmelCase    ,					_lowerCAmelCase    ,					"NoAns"						)
      if OPTS.na_prob_file:
            find_all_best_thresh(_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase						)
      if OPTS.na_prob_file and OPTS.out_image_dir:
            run_precision_recall_analysis(_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					_lowerCAmelCase    ,					OPTS.out_image_dir						)
            histogram_na_prob(_lowerCAmelCase    ,					_lowerCAmelCase    ,					OPTS.out_image_dir    ,					"hasAns"						)
            histogram_na_prob(_lowerCAmelCase    ,					_lowerCAmelCase    ,					OPTS.out_image_dir    ,					"noAns"						)
      if OPTS.out_file:
            with open(OPTS.out_file    ,					"w"						) as f:
                  json.dump(_lowerCAmelCase    ,					_lowerCAmelCase						)
      else:
            print(json.dumps(_lowerCAmelCase    ,					indent=2						)						)


if __name__ == "__main__":
    A      :    Any		=					parse_args()
    if OPTS.out_image_dir:
        import matplotlib

        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
    main()







'''simple docstring'''





import argparse
import json
import os

import fairseq
import torch
from torch import nn

from transformers import (
    SpeechaTextaConfig,
    SpeechaTextaForCausalLM,
    SpeechaTextaTokenizer,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    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_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": "lm_head",
    "mask_emb": "masked_spec_embed",
}
__a          =		[
    "lm_head",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
]





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)		-> Union[str, Any]:
      for attribute in key.split("""."""		):
            snake_case__  :    Dict    						=      getattr(_lowerCAmelCase     ,   _lowerCAmelCase		)

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

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





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase		)		-> Any:
      snake_case__  :    Union[str, Any]    						=      []
      snake_case__  :    Dict    						=      fairseq_model.state_dict()

      snake_case__  :    List[Any]    						=      hf_model.feature_extractor

      # if encoder has different dim to decoder -> use proj_weight
      snake_case__  :    Optional[int]    						=      None

      for name, value in fairseq_dict.items():
            snake_case__  :    List[Any]    						=      False
            if "conv_layers" in name:
                  load_conv_layer(
                      _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   hf_model.config.feat_extract_norm == """group"""     ,   )
                  snake_case__  :    Union[str, Any]    						=      True
            elif name.split("""."""		)[0] == "proj":
                  snake_case__  :    Tuple    						=      fairseq_model.proj
                  snake_case__  :    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[Any]    						=      True
                              if "*" in mapped_key:
                                    snake_case__  :    Optional[int]    						=      name.split(_lowerCAmelCase		)[0].split("""."""		)[-2]
                                    snake_case__  :    Tuple    						=      mapped_key.replace("""*"""     ,   _lowerCAmelCase		)
                              if "weight_g" in name:
                                    snake_case__  :    str    						=      """weight_g"""
                              elif "weight_v" in name:
                                    snake_case__  :    int    						=      """weight_v"""
                              elif "bias" in name:
                                    snake_case__  :    Dict    						=      """bias"""
                              elif "weight" in name:
                                    snake_case__  :    Union[str, Any]    						=      """weight"""
                              else:
                                    snake_case__  :    Union[str, Any]    						=      None
                              set_recursively(_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)
                        continue
            if not is_used:
                  unused_weights.append(_lowerCAmelCase		)

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

      return proj_weight





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)		-> Dict:
      snake_case__  :    int    						=      full_name.split("""conv_layers."""		)[-1]
      snake_case__  :    Dict    						=      name.split("""."""		)
      snake_case__  :    Any    						=      int(items[0]		)
      snake_case__  :    Optional[Any]    						=      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__  :    int    						=      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__  :    str    						=      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__  :    Union[str, Any]    						=      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__  :    int    						=      value
                  logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."		)
      else:
            unused_weights.append(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      snake_case__						,				snake_case__  :    str    						=      emb.weight.shape
      snake_case__  :    List[str]    						=      nn.Linear(_lowerCAmelCase     ,   _lowerCAmelCase     ,   bias=_lowerCAmelCase		)
      snake_case__  :    List[str]    						=      emb.weight.data
      return lin_layer





def 						__snake_case(				_lowerCAmelCase		)		-> Optional[Any]:
      with open(_lowerCAmelCase     ,   """r"""     ,   encoding="""utf-8"""		) as f:
            snake_case__  :    int    						=      f.readlines()
            snake_case__  :    List[Any]    						=      [line.split(""" """		)[0] for line in lines]

      snake_case__  :    Union[str, Any]    						=      len(_lowerCAmelCase		)

      snake_case__  :    Any    						=      {
          """<s>""": 0,
          """<pad>""": 1,
          """</s>""": 2,
          """<unk>""": 3,
      }

      vocab_dict.update(dict(zip(_lowerCAmelCase     ,   range(4     ,   num_words + 4		)		)		)		)
      return vocab_dict





@torch.no_grad()
def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   )		-> int:
      snake_case__  :    Optional[Any]    						=      WavaVecaConfig.from_pretrained(_lowerCAmelCase		)
      snake_case__  :    Optional[Any]    						=      SpeechaTextaConfig.from_pretrained(
          _lowerCAmelCase     ,   vocab_size=_lowerCAmelCase     ,   decoder_layers=_lowerCAmelCase     ,   do_stable_layer_norm=_lowerCAmelCase		)

      snake_case__  :    Optional[Any]    						=      WavaVecaFeatureExtractor(
          feature_size=1     ,   sampling_rate=16_000     ,   padding_value=0     ,   do_normalize=_lowerCAmelCase     ,   return_attention_mask=_lowerCAmelCase     ,   )

      snake_case__						,				snake_case__						,				snake_case__  :    Union[str, Any]    						=      fairseq.checkpoint_utils.load_model_ensemble_and_task(
          [checkpoint_path]     ,   arg_overrides={"""data""": """/""".join(dict_path.split("""/"""		)[:-1]		)}		)
      snake_case__  :    Tuple    						=      model[0].eval()

      # set weights for wav2vec2 encoder
      snake_case__  :    Optional[Any]    						=      WavaVecaModel(_lowerCAmelCase		)
      snake_case__  :    Dict    						=      recursively_load_weights_wavaveca(model.encoder     ,   _lowerCAmelCase		)

      snake_case__  :    Optional[Any]    						=      SpeechaTextaForCausalLM(_lowerCAmelCase		)
      snake_case__						,				snake_case__  :    Tuple    						=      hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()     ,   strict=_lowerCAmelCase		)

      # set output linear layer
      unexpected_keys.remove("""embed_out"""		)
      snake_case__  :    Tuple    						=      nn.Parameter(model.decoder.embed_out.detach()		)

      # layer norm is init to identity matrix so leaving it is fine
      logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}"		)
      logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}"		)

      snake_case__  :    List[Any]    						=      SpeechEncoderDecoderModel(encoder=_lowerCAmelCase     ,   decoder=_lowerCAmelCase		)
      snake_case__  :    Tuple    						=      False

      # add projection layer
      snake_case__  :    Union[str, Any]    						=      nn.Parameter(projection_layer.weight		)
      snake_case__  :    int    						=      nn.Parameter(projection_layer.bias		)

      snake_case__  :    Tuple    						=      create_vocab_dict(_lowerCAmelCase		)

      with open(os.path.join(_lowerCAmelCase     ,   """vocab.json"""		)     ,   """w"""		) as fp:
            json.dump(_lowerCAmelCase     ,   _lowerCAmelCase		)

      snake_case__  :    Tuple    						=      SpeechaTextaTokenizer(os.path.join(_lowerCAmelCase     ,   """vocab.json"""		)		)
      tokenizer.save_pretrained(_lowerCAmelCase		)

      snake_case__  :    Optional[Any]    						=      hf_wavavec.config.to_dict()
      snake_case__  :    Tuple    						=      tokenizer.pad_token_id
      snake_case__  :    Optional[Any]    						=      tokenizer.bos_token_id
      snake_case__  :    int    						=      tokenizer.eos_token_id
      snake_case__  :    str    						=      """speech_to_text_2"""
      snake_case__  :    List[Any]    						=      """wav2vec2"""

      snake_case__  :    List[str]    						=      SpeechEncoderDecoderConfig.from_dict(_lowerCAmelCase		)

      hf_wavavec.save_pretrained(_lowerCAmelCase		)
      feature_extractor.save_pretrained(_lowerCAmelCase		)


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("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
       parser.add_argument(
           "--encoder_config_path",
           default="facebook/wav2vec2-large-lv60",
           type=str,
           help="Path to hf encoder wav2vec2 checkpoint config",
       )
       parser.add_argument(
           "--decoder_config_path",
           default="facebook/s2t-small-mustc-en-fr-st",
           type=str,
           help="Path to hf decoder s2t checkpoint config",
       )
       parser.add_argument("--vocab_size", default=1_0224, type=int, help="Vocab size of decoder")
       parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers")

       __a          =		parser.parse_args()
       convert_wavaveca_checkpoint(
           args.checkpoint_path,
           args.pytorch_dump_folder_path,
           args.dict_path,
           encoder_config_path=args.encoder_config_path,
           decoder_config_path=args.decoder_config_path,
           vocab_size=args.vocab_size,
           num_decoder_layers=args.num_decoder_layers,
       )
