



'''simple docstring'''






from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


lowerCAmelCase:      Any		 =		'\\n@article{wang2019superglue,\n  title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n  author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n  journal={arXiv preprint arXiv:1905.00537},\n  year={2019}\n}\n'

lowerCAmelCase:      Optional[int]		 =		'\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n'

lowerCAmelCase:      Union[str, Any]		 =		'\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n    predictions: list of predictions to score. Depending on the SuperGlUE subset:\n        - for \'record\': list of question-answer dictionaries with the following keys:\n            - \'idx\': index of the question as specified by the dataset\n            - \'prediction_text\': the predicted answer text\n        - for \'multirc\': list of question-answer dictionaries with the following keys:\n            - \'idx\': index of the question-answer pair as specified by the dataset\n            - \'prediction\': the predicted answer label\n        - otherwise: list of predicted labels\n    references: list of reference labels. Depending on the SuperGLUE subset:\n        - for \'record\': list of question-answers dictionaries with the following keys:\n            - \'idx\': index of the question as specified by the dataset\n            - \'answers\': list of possible answers\n        - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n    - for \'record\':\n        - \'exact_match\': Exact match between answer and gold answer\n        - \'f1\': F1 score\n    - for \'multirc\':\n        - \'exact_match\': Exact match between answer and gold answer\n        - \'f1_m\': Per-question macro-F1 score\n        - \'f1_a\': Average F1 score over all answers\n    - for \'axb\':\n        \'matthews_correlation\': Matthew Correlation\n    - for \'cb\':\n        - \'accuracy\': Accuracy\n        - \'f1\': F1 score\n    - for all others:\n        - \'accuracy\': Accuracy\nExamples:\n\n    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\')  # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n    >>> predictions = [0, 1]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'accuracy\': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n    >>> predictions = [0, 1]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'accuracy\': 1.0, \'f1\': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n    >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n    >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 1.0, \'f1\': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n    >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'matthews_correlation\': 1.0}\n'
def    lowerCamelCase__ (		_A				,    _A       ):
  return float((preds == labels).mean()       )
def    lowerCamelCase__ (		_A				,    _A				,    _A="binary"       ):
  a		:      List[str]       =  simple_accuracy(_A				,    _A       )
  a		:      List[Any]       =  float(fa_score(y_true=_A				,    y_pred=_A				,    average=_A       )       )
  return {
      "accuracy": acc,
      "f1": fa,
  }
def    lowerCamelCase__ (		_A				,    _A       ):
  a		:      Optional[Any]       =  {}
  for id_pred, label in zip(_A				,    _A       ):
    a		:      List[str]       =  f"""{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}"""
    a		:      str       =  id_pred['prediction']
    if question_id in question_map:
      question_map[question_id].append((pred, label)       )
    else:
      a		:      int       =  [(pred, label)]
  a     ,			a		:      Union[str, Any]       =  [], []
  for question, preds_labels in question_map.items():
    a     ,			a		:      Any       =  zip(*_A       )
    a		:      Dict       =  fa_score(y_true=_A				,    y_pred=_A				,    average='macro'       )
    fas.append(_A       )
    a		:      Optional[int]       =  int(sum(pred == label for pred, label in preds_labels       ) == len(_A       )       )
    ems.append(_A       )
  a		:      List[Any]       =  float(sum(_A       ) / len(_A       )       )
  a		:      int       =  sum(_A       ) / len(_A       )
  a		:      str       =  float(fa_score(y_true=_A				,    y_pred=[id_pred['prediction'] for id_pred in ids_preds]       )       )
  return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a}

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,				_KWARGS_DESCRIPTION			)
class 							a__(      datasets.Metric			):







    def     lowercase_ (   self				:						Optional[int]			):
      if self.config_name not in [
          "boolq",
          "cb",
          "copa",
          "multirc",
          "record",
          "rte",
          "wic",
          "wsc",
          "wsc.fixed",
          "axb",
          "axg",
      ]:
        raise KeyError(
            'You should supply a configuration name selected in '
            '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]'			)
      return datasets.MetricInfo(
          description=_DESCRIPTION		,    citation=_CITATION		,    inputs_description=_KWARGS_DESCRIPTION		,    features=datasets.Features(self._get_feature_types()			)		,    codebase_urls=[]		,    reference_urls=[]		,    format='numpy' if not self.config_name == 'record' and not self.config_name == 'multirc' else None		,    )







    def     lowercase_ (   self				:						Dict			):
      if self.config_name == "record":
        return {
            "predictions": {
                "idx": {
                    "passage": datasets.Value('int64'			),
                    "query": datasets.Value('int64'			),
                },
                "prediction_text": datasets.Value('string'			),
            },
            "references": {
                "idx": {
                    "passage": datasets.Value('int64'			),
                    "query": datasets.Value('int64'			),
                },
                "answers": datasets.Sequence(datasets.Value('string'			)			),
            },
        }
      elif self.config_name == "multirc":
        return {
            "predictions": {
                "idx": {
                    "answer": datasets.Value('int64'			),
                    "paragraph": datasets.Value('int64'			),
                    "question": datasets.Value('int64'			),
                },
                "prediction": datasets.Value('int64'			),
            },
            "references": datasets.Value('int64'			),
        }
      else:
        return {
            "predictions": datasets.Value('int64'			),
            "references": datasets.Value('int64'			),
        }







    def     lowercase_ (   self				:						int		,    __snake_case				:						Optional[Any]		,    __snake_case				:						int			):
      if self.config_name == "axb":
        return {"matthews_correlation": matthews_corrcoef(__snake_case		,    __snake_case			)}
      elif self.config_name == "cb":
        return acc_and_fa(__snake_case		,    __snake_case		,    fa_avg='macro'			)
      elif self.config_name == "record":
        a		:      str       =  [
            {
                'qas': [
                    {'id': ref['idx']['query'], 'answers': [{'text': ans} for ans in ref['answers']]}
                    for ref in references
                ]
            }
        ]
        a		:      List[str]       =  {pred['idx']['query']: pred['prediction_text'] for pred in predictions}
        return evaluate_record(__snake_case		,    __snake_case			)[0]
      elif self.config_name == "multirc":
        return evaluate_multirc(__snake_case		,    __snake_case			)
      elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]:
        return {"accuracy": simple_accuracy(__snake_case		,    __snake_case			)}
      else:
        raise KeyError(
            'You should supply a configuration name selected in '
            '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]'			)




'''simple docstring'''






import argparse

import fairseq
import torch

from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging


logging.set_verbosity_info()
lowerCAmelCase:      Optional[int]		 =		logging.get_logger(__name__)

lowerCAmelCase:      Union[str, Any]		 =		{
    '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',
    'encoder.layer_norm_for_extract': 'layer_norm_for_extract',
    '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',
    'label_embs_concat': 'label_embeddings_concat',
    'mask_emb': 'masked_spec_embed',
    'spk_proj': 'speaker_proj',
}
lowerCAmelCase:      int		 =		[
    'lm_head',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
    'label_embeddings_concat',
    'speaker_proj',
    'layer_norm_for_extract',
]
def    lowerCamelCase__ (		_A				,    _A				,    _A				,    _A				,    _A       ):
  for attribute in key.split('.'       ):
    a		:      Tuple       =  getattr(_A				,    _A       )

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

  logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}."""       )
def    lowerCamelCase__ (		_A				,    _A       ):
  a		:      Optional[int]       =  []
  a		:      Tuple       =  fairseq_model.state_dict()

  a		:      List[Any]       =  hf_model.unispeech_sat.feature_extractor

  for name, value in fairseq_dict.items():
    a		:      Optional[Any]       =  False
    if "conv_layers" in name:
      load_conv_layer(
          _A				,    _A				,    _A				,    _A				,    hf_model.config.feat_extract_norm == 'group'				,    )
      a		:      int       =  True
    else:
      for key, mapped_key in MAPPING.items():
        a		:      Any       =  'unispeech_sat.' + 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]:
          if "layer_norm_for_extract" in name and (".".join(name.split('.'       )[:-1]       ) != key):
            # special case since naming is very similar
            continue
          a		:      str       =  True
          if "*" in mapped_key:
            a		:      Union[str, Any]       =  name.split(_A       )[0].split('.'       )[-2]
            a		:      List[str]       =  mapped_key.replace('*'				,    _A       )
          if "weight_g" in name:
            a		:      Optional[int]       =  'weight_g'
          elif "weight_v" in name:
            a		:      Any       =  'weight_v'
          elif "bias" in name:
            a		:      str       =  'bias'
          elif "weight" in name:
            # TODO: don't match quantizer.weight_proj
            a		:      List[Any]       =  'weight'
          else:
            a		:      Any       =  None
          set_recursively(_A				,    _A				,    _A				,    _A				,    _A       )
        continue
    if not is_used:
      unused_weights.append(_A       )

  logger.warning(f"""Unused weights: {unused_weights}"""       )
def    lowerCamelCase__ (		_A				,    _A				,    _A				,    _A				,    _A       ):
  a		:      List[str]       =  full_name.split('conv_layers.'       )[-1]
  a		:      Any       =  name.split('.'       )
  a		:      Optional[Any]       =  int(items[0]       )
  a		:      Union[str, Any]       =  int(items[1]       )

  if type_id == 0:
    if "bias" in name:
      if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
        raise ValueError(
            f"""{full_name} has size {value.shape}, but"""
            f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""       )
      a		:      Optional[int]       =  value
      logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}."""       )
    elif "weight" in name:
      if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
        raise ValueError(
            f"""{full_name} has size {value.shape}, but"""
            f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""       )
      a		:      Optional[int]       =  value
      logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}."""       )
  elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
    if "bias" in name:
      if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
        raise ValueError(
            f"""{full_name} has size {value.shape}, but"""
            f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found."""       )
      a		:      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:
      if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
        raise ValueError(
            f"""{full_name} has size {value.shape}, but"""
            f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."""       )
      a		:      Union[str, Any]       =  value
      logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""       )
  else:
    unused_weights.append(_A       )
@torch.no_grad()
def    lowerCamelCase__ (		_A				,    _A				,    _A=None				,    _A=None				,    _A=True       ):
  if config_path is not None:
    a		:      str       =  UniSpeechSatConfig.from_pretrained(_A       )
  else:
    a		:      Dict       =  UniSpeechSatConfig()

  a		:      Any       =  ''

  if is_finetuned:
    a		:      Tuple       =  UniSpeechSatForCTC(_A       )
  else:
    a		:      List[str]       =  UniSpeechSatForPreTraining(_A       )

  a     ,			a     ,			a		:      str       =  fairseq.checkpoint_utils.load_model_ensemble_and_task(
      [checkpoint_path]				,    arg_overrides={'data': '/'.join(dict_path.split('/'       )[:-1]       )}       )
  a		:      str       =  model[0].eval()

  recursively_load_weights(_A				,    _A       )

  hf_wavavec.save_pretrained(_A       )


if __name__ == "__main__":
     lowerCAmelCase:      Tuple		 =		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'
     )
     lowerCAmelCase:      Optional[int]		 =		parser.parse_args()
     convert_unispeech_sat_checkpoint(
         args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
     )