'''simple docstring'''


import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed

import numpy as np

import datasets

from .execute import check_correctness


__snake_case						  =		"""\
@misc{chen2021evaluating,
      title={Evaluating Large Language Models Trained on Code},
      author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
and William Saunders and Christopher Hesse and Andrew N. Carr \
and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
      year={2021},
      eprint={2107.03374},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}
"""

__snake_case						  =		"""\
This metric implements the evaluation harness for the HumanEval problem solving dataset
described in the paper \"Evaluating Large Language Models Trained on Code\"
(https://arxiv.org/abs/2107.03374).
"""


__snake_case						  =		"""
Calculates how good are predictions given some references, using certain scores
Args:
    predictions: list of candidates to evaluate. Each candidates should be a list
        of strings with several code candidates to solve the problem.
    references: a list with a test for each prediction. Each test should evaluate the
        correctness of a code candidate.
    k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
    num_workers: number of workers used to evaluate the canidate programs (Default: 4).
    timeout:
Returns:
    pass_at_k: dict with pass rates for each k
    results: dict with granular results of each unittest
Examples:
    >>> code_eval = datasets.load_metric(\"code_eval\")
    >>> test_cases = [\"assert add(2,3)==5\"]
    >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]
    >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
    >>> print(pass_at_k)
    {'pass@1': 0.5, 'pass@2': 1.0}
"""


__snake_case						  =		"""
################################################################################
                                  !!!WARNING!!!
################################################################################
The \"code_eval\" metric executes untrusted model-generated code in Python.
Although it is highly unlikely that model-generated code will do something
overtly malicious in response to this test suite, model-generated code may act
destructively due to a lack of model capability or alignment.
Users are strongly encouraged to sandbox this evaluation suite so that it
does not perform destructive actions on their host or network. For more
information on how OpenAI sandboxes its code, see the paper \"Evaluating Large
Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374).

Once you have read this disclaimer and taken appropriate precautions,
set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this
with:

>>> import os
>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"

################################################################################\
"""

__snake_case						  =		"""The MIT License

Copyright (c) OpenAI (https://openai.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE."""





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


  """simple docstring"""

  def 		lowerCamelCase__  (		self      :       Dict      ):







    '''simple docstring'''


    return datasets.MetricInfo(
        # This is the description that will appear on the metrics page.
        description=_DESCRIPTION   ,				citation=_CITATION   ,				inputs_description=_KWARGS_DESCRIPTION   ,				features=datasets.Features(
            {
                """predictions""": datasets.Sequence(datasets.Value("""string"""      )      ),
                """references""": datasets.Value("""string"""      ),
            }      )   ,				homepage="""https://github.com/openai/human-eval"""   ,				codebase_urls=["""https://github.com/openai/human-eval"""]   ,				reference_urls=["""https://github.com/openai/human-eval"""]   ,				license=_LICENSE   ,				)





  def 		lowerCamelCase__  (		self      :       Union[str, Any]   ,				lowercase_      :       Any   ,				lowercase_      :       str   ,				lowercase_      :       List[str]=[1, 10, 100]   ,				lowercase_      :       int=4   ,				lowercase_      :       Dict=3.0      ):







    '''simple docstring'''


    if os.getenv("""HF_ALLOW_CODE_EVAL"""   ,				0      ) != "1":
      raise ValueError(_WARNING      )

    if os.name == "nt":
      raise NotImplementedError("""This metric is currently not supported on Windows."""      )

    with ThreadPoolExecutor(max_workers=lowercase_      ) as executor:
      lowercase_     =       []
      lowercase_     =       Counter()
      lowercase_     =       0
      lowercase_     =       defaultdict(lowercase_      )

      for task_id, (candidates, test_case) in enumerate(zip(lowercase_   ,				lowercase_      )      ):
        for candidate in candidates:
          lowercase_     =       candidate + """\n""" + test_case
          lowercase_     =       (test_program, timeout, task_id, completion_id[task_id])
          lowercase_     =       executor.submit(lowercase_   ,				*lowercase_      )
          futures.append(lowercase_      )
          completion_id[task_id] += 1
          n_samples += 1

      for future in as_completed(lowercase_      ):
        lowercase_     =       future.result()
        results[result["task_id"]].append((result["""completion_id"""], result)      )

    lowercase_     ,	lowercase_     =       [], []
    for result in results.values():
      result.sort()
      lowercase_     =       [r[1]["""passed"""] for r in result]
      total.append(len(lowercase_      )      )
      correct.append(sum(lowercase_      )      )
    lowercase_     =       np.array(lowercase_      )
    lowercase_     =       np.array(lowercase_      )

    lowercase_     =       k
    lowercase_     =       {F"""pass@{k}""": estimate_pass_at_k(lowercase_   ,				lowercase_   ,				lowercase_      ).mean() for k in ks if (total >= k).all()}

    return pass_at_k, results






def   A_      (       SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)			->Optional[int]:

  def estimator(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						) -> float:
    if n - c < k:
      return 1.0
    return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 ,	n + 1						)						)

  if isinstance(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						):
    lowercase_     =       itertools.repeat(SCREAMING_SNAKE_CASE_ ,	len(SCREAMING_SNAKE_CASE_						)						)
  else:
    assert len(SCREAMING_SNAKE_CASE_						) == len(SCREAMING_SNAKE_CASE_						)
    lowercase_     =       iter(SCREAMING_SNAKE_CASE_						)

  return np.array([estimator(int(SCREAMING_SNAKE_CASE_						) ,	int(SCREAMING_SNAKE_CASE_						) ,	SCREAMING_SNAKE_CASE_						) for n, c in zip(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)]						)


'''simple docstring'''


import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

# Register SEW's fairseq modules
from sew_asapp import tasks  # noqa: F401

from transformers import (
    SEWConfig,
    SEWForCTC,
    SEWModel,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
    logging,
)


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

__snake_case						  =		{
    """post_extract_proj""": """feature_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.upsample.0""": """encoder.upsample.projection""",
    """encoder.layer_norm""": """encoder.layer_norm""",
    """w2v_model.layer_norm""": """layer_norm""",
    """w2v_encoder.proj""": """lm_head""",
    """mask_emb""": """masked_spec_embed""",
}

def   A_      (       SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)			->Any:
  for attribute in key.split("""."""						):
    lowercase_     =       getattr(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)

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

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

def   A_      (       SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)			->Union[str, Any]:
  lowercase_     =       []
  lowercase_     =       fairseq_model.state_dict()

  lowercase_     =       hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor

  for name, value in fairseq_dict.items():
    lowercase_     =       False
    if "conv_layers" in name:
      load_conv_layer(
          SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	hf_model.config.feat_extract_norm == """group""" ,	)
      lowercase_     =       True
    else:
      for key, mapped_key in MAPPING.items():
        lowercase_     =       """sew.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key

        if key in name or key.split("""w2v_model."""						)[-1] == name.split("""."""						)[0]:
          lowercase_     =       True
          if "*" in mapped_key:
            lowercase_     =       name.split(SCREAMING_SNAKE_CASE_						)[0].split("""."""						)[-2]
            lowercase_     =       mapped_key.replace("""*""" ,	SCREAMING_SNAKE_CASE_						)
          if "weight_g" in name:
            lowercase_     =       """weight_g"""
          elif "weight_v" in name:
            lowercase_     =       """weight_v"""
          elif "weight" in name:
            lowercase_     =       """weight"""
          elif "bias" in name:
            lowercase_     =       """bias"""
          else:
            lowercase_     =       None
          set_recursively(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)
        continue
    if not is_used:
      unused_weights.append(SCREAMING_SNAKE_CASE_						)

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

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

def   A_      (       SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)			->List[str]:
  lowercase_     =       SEWConfig()
  if is_finetuned:
    lowercase_     =       model.wav_encoder.wav_model.cfg
  else:
    lowercase_     =       model.cfg

  lowercase_     =       fs_config.conv_bias
  lowercase_     =       eval(fs_config.conv_feature_layers						)
  lowercase_     =       [x[0] for x in conv_layers]
  lowercase_     =       [x[1] for x in conv_layers]
  lowercase_     =       [x[2] for x in conv_layers]
  lowercase_     =       """gelu"""
  lowercase_     =       """layer""" if fs_config.extractor_mode == """layer_norm""" else """group"""
  lowercase_     =       0.0
  lowercase_     =       fs_config.activation_fn.name
  lowercase_     =       fs_config.encoder_embed_dim
  lowercase_     =       0.02
  lowercase_     =       fs_config.encoder_ffn_embed_dim
  lowercase_     =       1e-5
  lowercase_     =       fs_config.encoder_layerdrop
  lowercase_     =       fs_config.encoder_attention_heads
  lowercase_     =       fs_config.conv_pos_groups
  lowercase_     =       fs_config.conv_pos
  lowercase_     =       len(SCREAMING_SNAKE_CASE_						)
  lowercase_     =       fs_config.encoder_layers
  lowercase_     =       fs_config.squeeze_factor

  # take care of any params that are overridden by the Wav2VecCtc model
  if is_finetuned:
    lowercase_     =       model.cfg
    lowercase_     =       fs_config.final_dropout
    lowercase_     =       fs_config.layerdrop
  lowercase_     =       fs_config.activation_dropout
  lowercase_     =       fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
  lowercase_     =       fs_config.attention_dropout
  lowercase_     =       fs_config.dropout_input
  lowercase_     =       fs_config.dropout
  lowercase_     =       fs_config.mask_channel_length
  lowercase_     =       fs_config.mask_channel_prob
  lowercase_     =       fs_config.mask_length
  lowercase_     =       fs_config.mask_prob

  lowercase_     =       """Wav2Vec2FeatureExtractor"""
  lowercase_     =       """Wav2Vec2CTCTokenizer"""

  return config

@torch.no_grad()
def   A_      (       SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_=None ,	SCREAMING_SNAKE_CASE_=None ,	SCREAMING_SNAKE_CASE_=True						)			->Optional[Any]:

  if is_finetuned:
    lowercase_     ,	lowercase_     ,	lowercase_     =       fairseq.checkpoint_utils.load_model_ensemble_and_task(
        [checkpoint_path] ,	arg_overrides={"""data""": """/""".join(dict_path.split("""/"""						)[:-1]						)}						)
  else:
    lowercase_     ,	lowercase_     ,	lowercase_     =       fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]						)

  if config_path is not None:
    lowercase_     =       SEWConfig.from_pretrained(SCREAMING_SNAKE_CASE_						)
  else:
    lowercase_     =       convert_config(model[0] ,	SCREAMING_SNAKE_CASE_						)
  lowercase_     =       model[0].eval()

  lowercase_     =       True if config.feat_extract_norm == """layer""" else False
  lowercase_     =       WavaVecaFeatureExtractor(
      feature_size=1 ,	sampling_rate=1_60_00 ,	padding_value=0 ,	do_normalize=SCREAMING_SNAKE_CASE_ ,	return_attention_mask=SCREAMING_SNAKE_CASE_ ,	)

  if is_finetuned:
    if dict_path:
      lowercase_     =       Dictionary.load(SCREAMING_SNAKE_CASE_						)

      # important change bos & pad token id since CTC symbol is <pad> and
      # not <s> as in fairseq
      lowercase_     =       target_dict.pad_index
      lowercase_     =       target_dict.bos_index
      lowercase_     =       target_dict.pad_index
      lowercase_     =       target_dict.bos_index
      lowercase_     =       target_dict.eos_index
      lowercase_     =       len(target_dict.symbols						)
      lowercase_     =       os.path.join(SCREAMING_SNAKE_CASE_ ,	"""vocab.json"""						)
      if not os.path.isdir(SCREAMING_SNAKE_CASE_						):
        logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(SCREAMING_SNAKE_CASE_						)						)
        return
      os.makedirs(SCREAMING_SNAKE_CASE_ ,	exist_ok=SCREAMING_SNAKE_CASE_						)
      with open(SCREAMING_SNAKE_CASE_ ,	"""w""" ,	encoding="""utf-8"""						) as vocab_handle:
        json.dump(target_dict.indices ,	SCREAMING_SNAKE_CASE_						)
      lowercase_     =       WavaVecaCTCTokenizer(
          SCREAMING_SNAKE_CASE_ ,	unk_token=target_dict.unk_word ,	pad_token=target_dict.pad_word ,	bos_token=target_dict.bos_word ,	eos_token=target_dict.eos_word ,	word_delimiter_token="""|""" ,	do_lower_case=SCREAMING_SNAKE_CASE_ ,	)
      lowercase_     =       WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE_ ,	tokenizer=SCREAMING_SNAKE_CASE_						)
      processor.save_pretrained(SCREAMING_SNAKE_CASE_						)

    lowercase_     =       SEWForCTC(SCREAMING_SNAKE_CASE_						)
  else:
    lowercase_     =       SEWModel(SCREAMING_SNAKE_CASE_						)
    feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_						)

  recursively_load_weights(SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_ ,	SCREAMING_SNAKE_CASE_						)

  hf_model.save_pretrained(SCREAMING_SNAKE_CASE_						)


if __name__ == "__main__":
       __snake_case						  =		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(
           """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
       )
       __snake_case						  =		parser.parse_args()
       convert_sew_checkpoint(
           args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
       )

