

'''simple docstring'''

import argparse
import pathlib
from pathlib import Path
from tempfile import TemporaryDirectory

import esm as esm_module
import torch
from esm.esmfold.va.misc import batch_encode_sequences as esmfold_encode_sequences
from esm.esmfold.va.pretrained import esmfold_va

from transformers.models.esm.configuration_esm import EsmConfig, EsmFoldConfig
from transformers.models.esm.modeling_esm import (
    EsmForMaskedLM,
    EsmForSequenceClassification,
    EsmIntermediate,
    EsmLayer,
    EsmOutput,
    EsmSelfAttention,
    EsmSelfOutput,
)
from transformers.models.esm.modeling_esmfold import EsmForProteinFolding
from transformers.models.esm.tokenization_esm import EsmTokenizer
from transformers.utils import logging


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

lowercase__            =     [
    (
        "protein1",
        "MNGTEGPNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQHKKLRTPLNYILLNLAVADLFMVLGGFTSTLYTSLHGYFVFGPTGCNLEGFFATLGGEIALWSLVVLAIERYVVVCKPMSNFRFGENHAIMGVAFTWVMALACAAPPLAGWSRYIPEGLQCSCGIDYYTLKPEVNNESFVIYMFVVHFTIPMIIIFFCYGQLVFTVKEAAAQQQESATTQKAEKEVTRMVIIMVIAFLICWVPYASVAFYIFTHQGSNFGPIFMTIPAFFAKSAAIYNPVIYIMMNKQFRNCMLTTICCGKNPLGDDEASATVSKTETSQVAPA",
    ),
    ("protein2", "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLA"),
    ("protein3", "MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLAGG"),
    ("protein4", "MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLA"),
]

lowercase__            =     {
    "esm1b_t33_650M_UR50S": esm_module.pretrained.esm1b_t33_650M_UR50S,
    "esm1v_t33_650M_UR90S_1": esm_module.pretrained.esm1v_t33_650M_UR90S_1,
    "esm1v_t33_650M_UR90S_2": esm_module.pretrained.esm1v_t33_650M_UR90S_2,
    "esm1v_t33_650M_UR90S_3": esm_module.pretrained.esm1v_t33_650M_UR90S_3,
    "esm1v_t33_650M_UR90S_4": esm_module.pretrained.esm1v_t33_650M_UR90S_4,
    "esm1v_t33_650M_UR90S_5": esm_module.pretrained.esm1v_t33_650M_UR90S_5,
    "esm2_t48_15B_UR50D": esm_module.pretrained.esm2_t48_15B_UR50D,
    "esm2_t36_3B_UR50D": esm_module.pretrained.esm2_t36_3B_UR50D,
    "esm2_t33_650M_UR50D": esm_module.pretrained.esm2_t33_650M_UR50D,
    "esm2_t30_150M_UR50D": esm_module.pretrained.esm2_t30_150M_UR50D,
    "esm2_t12_35M_UR50D": esm_module.pretrained.esm2_t12_35M_UR50D,
    "esm2_t6_8M_UR50D": esm_module.pretrained.esm2_t6_8M_UR50D,
    "esmfold_v1": esmfold_va,
}

lowercase__            =     list("ARNDCQEGHILKMFPSTWYV")

lowercase__            =     restypes + ["X"]
lowercase__            =     restypes_with_x + ["<pad>", "<mask>", "<cls>", "<sep>", "<eos>"]




def  UpperCamelCase(	):
 with TemporaryDirectory() as tempdir:
  UpperCAmelCase			:      Tuple		   =					'\n'.join(UpperCAmelCase_      )
  UpperCAmelCase			:      List[str]		   =					Path(UpperCAmelCase_      ) / 'vocab.txt'
  vocab_file.write_text(UpperCAmelCase_      )
  UpperCAmelCase			:      Union[str, Any]		   =					EsmTokenizer(vocab_file=str(UpperCAmelCase_      )      )
 UpperCAmelCase			:      List[str]		   =					0  # Overlaps with 'A' but that seems to be what they want
 return hf_tokenizer




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_      ):
 UpperCAmelCase			:      int		   =					our_module.load_state_dict(original_module.state_dict()      )
 if status.missing_keys:
  raise ValueError(F"""Missing keys: {status.missing_keys}"""      )
 if status.unexpected_keys:
  raise ValueError(F"""Unexpected keys: {status.unexpected_keys}"""      )




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_      ):
 if model.startswith('esmfold'      ):
  UpperCAmelCase			:      Tuple		   =					MODEL_MAPPING[model]()
 else:
  UpperCAmelCase   ,					UpperCAmelCase			:      int		   =					MODEL_MAPPING[model]()
 esm.eval()  # disable dropout

 if model.startswith('esmfold'      ):
  UpperCAmelCase			:      Union[str, Any]		   =					esm.esm.embed_dim
  UpperCAmelCase			:      Dict		   =					esm.esm.num_layers
  UpperCAmelCase			:      Union[str, Any]		   =					esm.esm.attention_heads
  UpperCAmelCase			:      Any		   =					4 * embed_dim
  UpperCAmelCase			:      Dict		   =					esm.esm.token_dropout
  UpperCAmelCase			:      Optional[int]		   =					False  # This code path does not exist in ESM-2
  UpperCAmelCase			:      Union[str, Any]		   =					'rotary'
  UpperCAmelCase			:      Dict		   =					True
  UpperCAmelCase			:      Tuple		   =					EsmFoldConfig()
  for key, val in esm.cfg.items():
   if hasattr(UpperCAmelCase_    ,			UpperCAmelCase_      ) and key != "trunk":
    setattr(UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_      )
  for key, val in esm.cfg.trunk.items():
   if hasattr(esmfold_config.trunk    ,			UpperCAmelCase_      ) and key != "structure_module":
    setattr(esmfold_config.trunk    ,			UpperCAmelCase_    ,			UpperCAmelCase_      )
  for key, val in esm.cfg.trunk.structure_module.items():
   if hasattr(esmfold_config.trunk.structure_module    ,			UpperCAmelCase_      ):
    setattr(esmfold_config.trunk.structure_module    ,			UpperCAmelCase_    ,			UpperCAmelCase_      )
 elif hasattr(UpperCAmelCase_    ,			'args'      ):
  # Indicates an ESM-1b or ESM-1v model
  UpperCAmelCase			:      Optional[Any]		   =					esm.args.embed_dim
  UpperCAmelCase			:      List[Any]		   =					esm.args.layers
  UpperCAmelCase			:      str		   =					esm.args.attention_heads
  UpperCAmelCase			:      int		   =					esm.args.ffn_embed_dim
  UpperCAmelCase			:      Dict		   =					esm.args.token_dropout
  UpperCAmelCase			:      List[str]		   =					True if esm.emb_layer_norm_before else False
  UpperCAmelCase			:      Dict		   =					'absolute'
  UpperCAmelCase			:      Optional[Any]		   =					False
  UpperCAmelCase			:      int		   =					None
 else:
  # Indicates an ESM-2 model
  UpperCAmelCase			:      Dict		   =					esm.embed_dim
  UpperCAmelCase			:      int		   =					esm.num_layers
  UpperCAmelCase			:      Optional[int]		   =					esm.attention_heads
  UpperCAmelCase			:      List[str]		   =					4 * embed_dim  # This is hardcoded in ESM-2
  UpperCAmelCase			:      Union[str, Any]		   =					esm.token_dropout
  UpperCAmelCase			:      List[Any]		   =					False  # This code path does not exist in ESM-2
  UpperCAmelCase			:      Any		   =					'rotary'
  UpperCAmelCase			:      Dict		   =					False
  UpperCAmelCase			:      Optional[int]		   =					None

 if is_folding_model:
  UpperCAmelCase			:      Optional[Any]		   =					esm.esm.alphabet
 UpperCAmelCase			:      Any		   =					tuple(alphabet.all_toks      )
 UpperCAmelCase			:      Union[str, Any]		   =					alphabet.mask_idx
 UpperCAmelCase			:      List[Any]		   =					alphabet.padding_idx

 if is_folding_model:
  UpperCAmelCase			:      Any		   =					esm.esm
 else:
  UpperCAmelCase			:      Dict		   =					esm

 UpperCAmelCase			:      int		   =					EsmConfig(
     vocab_size=original_esm_model.embed_tokens.num_embeddings    ,			mask_token_id=UpperCAmelCase_    ,			hidden_size=UpperCAmelCase_    ,			num_hidden_layers=UpperCAmelCase_    ,			num_attention_heads=UpperCAmelCase_    ,			intermediate_size=UpperCAmelCase_    ,			max_position_embeddings=10_26    ,			layer_norm_eps=1E-5    ,			attention_probs_dropout_prob=0.0    ,			hidden_dropout_prob=0.0    ,			pad_token_id=UpperCAmelCase_    ,			emb_layer_norm_before=UpperCAmelCase_    ,			token_dropout=UpperCAmelCase_    ,			position_embedding_type=UpperCAmelCase_    ,			is_folding_model=UpperCAmelCase_    ,			esmfold_config=UpperCAmelCase_    ,			vocab_list=UpperCAmelCase_    ,			)
 if classification_head:
  UpperCAmelCase			:      str		   =					esm.classification_heads['mnli'].out_proj.weight.shape[0]
 print('Our ESM config:'    ,			UpperCAmelCase_      )

 if model.startswith('esmfold'      ):
  UpperCAmelCase			:      str		   =					EsmForProteinFolding
 elif classification_head:
  UpperCAmelCase			:      List[str]		   =					EsmForSequenceClassification
 else:
  UpperCAmelCase			:      Tuple		   =					EsmForMaskedLM
 UpperCAmelCase			:      List[Any]		   =					model_class(UpperCAmelCase_      )
 model.eval()

 # Now let's copy all the weights.
 # Embeddings
 UpperCAmelCase			:      int		   =					original_esm_model.embed_tokens.weight
 if position_embedding_type == "absolute":
  UpperCAmelCase			:      int		   =					original_esm_model.embed_positions.weight

 if config.emb_layer_norm_before:
  UpperCAmelCase			:      Tuple		   =					original_esm_model.emb_layer_norm_before.weight
  UpperCAmelCase			:      Union[str, Any]		   =					original_esm_model.emb_layer_norm_before.bias

 UpperCAmelCase			:      Optional[int]		   =					original_esm_model.emb_layer_norm_after.weight
 UpperCAmelCase			:      Union[str, Any]		   =					original_esm_model.emb_layer_norm_after.bias

 for i in range(config.num_hidden_layers      ):
  # Encoder: start of layer
  UpperCAmelCase			:      EsmLayer		   =					model.esm.encoder.layer[i]
  # esm_layer: TransformerSentenceEncoderLayer = original_esm_model.layers[i]
  UpperCAmelCase			:      str		   =					original_esm_model.layers[i]

  # self attention
  UpperCAmelCase			:      EsmSelfAttention		   =					layer.attention.self
  assert (
      esm_layer.self_attn.k_proj.weight.data.shape
      == esm_layer.self_attn.q_proj.weight.data.shape
      == esm_layer.self_attn.v_proj.weight.data.shape
      == torch.Size((config.hidden_size, config.hidden_size)      )
  )

  UpperCAmelCase			:      Tuple		   =					esm_layer.self_attn.q_proj.weight
  UpperCAmelCase			:      Optional[Any]		   =					esm_layer.self_attn.q_proj.bias
  UpperCAmelCase			:      Tuple		   =					esm_layer.self_attn.k_proj.weight
  UpperCAmelCase			:      Any		   =					esm_layer.self_attn.k_proj.bias
  UpperCAmelCase			:      Any		   =					esm_layer.self_attn.v_proj.weight
  UpperCAmelCase			:      Any		   =					esm_layer.self_attn.v_proj.bias

  if getattr(esm_layer.self_attn    ,			'rot_emb'    ,			UpperCAmelCase_      ) is not None:
   # Matt: Although inv_freq is not a trainable weight, it is computed at model init and cached.
   # During the training of ESM-2 the model was converted to float16 precision, which also converts
   # the inv_freq tensor, and the loss of precision remains even if the model is loaded later as float32.
   # If we recompute inv_freq without this loss of precision then we will get subtly different rotary
   # embeddings, which are enough to cause significant discrepancies in model outputs. To avoid this,
   # we make sure the new model copies the data from the old inv_freq.
   UpperCAmelCase			:      str		   =					esm_layer.self_attn.rot_emb.inv_freq

  # LayerNorm changes for pre-activation
  UpperCAmelCase			:      Optional[int]		   =					esm_layer.self_attn_layer_norm.weight
  UpperCAmelCase			:      Any		   =					esm_layer.self_attn_layer_norm.bias
  UpperCAmelCase			:      List[str]		   =					esm_layer.final_layer_norm.weight
  UpperCAmelCase			:      Union[str, Any]		   =					esm_layer.final_layer_norm.bias

  # self-attention output
  UpperCAmelCase			:      EsmSelfOutput		   =					layer.attention.output
  assert self_output.dense.weight.shape == esm_layer.self_attn.out_proj.weight.shape
  UpperCAmelCase			:      Optional[int]		   =					esm_layer.self_attn.out_proj.weight
  UpperCAmelCase			:      Dict		   =					esm_layer.self_attn.out_proj.bias

  # intermediate
  UpperCAmelCase			:      EsmIntermediate		   =					layer.intermediate
  assert intermediate.dense.weight.shape == esm_layer.fca.weight.shape
  UpperCAmelCase			:      List[Any]		   =					esm_layer.fca.weight
  UpperCAmelCase			:      Optional[int]		   =					esm_layer.fca.bias

  # output
  UpperCAmelCase			:      EsmOutput		   =					layer.output
  assert bert_output.dense.weight.shape == esm_layer.fca.weight.shape
  UpperCAmelCase			:      List[Any]		   =					esm_layer.fca.weight
  UpperCAmelCase			:      int		   =					esm_layer.fca.bias
  # end of layer

 if is_folding_model:
  UpperCAmelCase			:      Optional[Any]		   =					esm.esm_s_combine.data
  UpperCAmelCase			:      Optional[Any]		   =					esm.afa_to_esm.data
  transfer_and_check_weights(esm.embedding    ,			model.embedding      )
  transfer_and_check_weights(esm.esm_s_mlp    ,			model.esm_s_mlp      )
  transfer_and_check_weights(esm.trunk    ,			model.trunk      )
  transfer_and_check_weights(esm.distogram_head    ,			model.distogram_head      )
  transfer_and_check_weights(esm.ptm_head    ,			model.ptm_head      )
  transfer_and_check_weights(esm.lm_head    ,			model.lm_head      )
  transfer_and_check_weights(esm.lddt_head    ,			model.lddt_head      )

 elif classification_head:
  UpperCAmelCase			:      List[Any]		   =					esm.esm.classification_heads['mnli'].dense.weight
  UpperCAmelCase			:      Dict		   =					esm.classification_heads['mnli'].dense.bias
  UpperCAmelCase			:      Tuple		   =					esm.classification_heads['mnli'].out_proj.weight
  UpperCAmelCase			:      Dict		   =					esm.classification_heads['mnli'].out_proj.bias
 else:
  # LM Head
  UpperCAmelCase			:      Dict		   =					esm.lm_head.dense.weight
  UpperCAmelCase			:      Union[str, Any]		   =					esm.lm_head.dense.bias
  UpperCAmelCase			:      List[str]		   =					esm.lm_head.layer_norm.weight
  UpperCAmelCase			:      Any		   =					esm.lm_head.layer_norm.bias
  UpperCAmelCase			:      Dict		   =					esm.lm_head.weight
  UpperCAmelCase			:      Any		   =					esm.lm_head.bias

 # Contact prediction head
 transfer_and_check_weights(esm.contact_head    ,			model.esm.contact_head      )

 # Prepare data (first 2 sequences from ESMStructuralSplitDataset superfamily / 4)
 if is_folding_model:
  # Folding models aren't trained on masked inputs and don't like mask tokens.
  UpperCAmelCase			:      Tuple		   =					SAMPLE_DATA[:2]
 else:
  UpperCAmelCase			:      Dict		   =					SAMPLE_DATA

 if is_folding_model:
  UpperCAmelCase			:      List[str]		   =					get_esmfold_tokenizer()
  UpperCAmelCase			:      Optional[int]		   =					hf_tokenizer(
      [row[1] for row in sample_data]    ,			return_tensors='pt'    ,			padding=UpperCAmelCase_    ,			add_special_tokens=UpperCAmelCase_      )
  UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase			:      List[str]		   =					esmfold_encode_sequences([row[1] for row in sample_data]      )
  UpperCAmelCase			:      int		   =					torch.all(hf_tokens['input_ids'] == esmfold_aas      ) and torch.all(
      hf_tokens['attention_mask'] == esmfold_mask      )
 else:
  # Let's check that we get the same results.
  UpperCAmelCase			:      Union[str, Any]		   =					alphabet.get_batch_converter()
  UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase			:      Any		   =					batch_converter(UpperCAmelCase_      )
  # Prepare tokenizer and make sure it matches
  with TemporaryDirectory() as tempdir:
   UpperCAmelCase			:      int		   =					'\n'.join(alphabet.all_toks      )
   UpperCAmelCase			:      List[str]		   =					Path(UpperCAmelCase_      ) / 'vocab.txt'
   vocab_file.write_text(UpperCAmelCase_      )
   UpperCAmelCase			:      List[Any]		   =					EsmTokenizer(vocab_file=str(UpperCAmelCase_      )      )

  UpperCAmelCase			:      Optional[int]		   =					hf_tokenizer([row[1] for row in sample_data]    ,			return_tensors='pt'    ,			padding=UpperCAmelCase_      )
  UpperCAmelCase			:      Union[str, Any]		   =					torch.all(hf_tokens['input_ids'] == batch_tokens      )

 print('Do both models tokenizers output the same tokens?'    ,			'🔥' if success else '💩'      )
 if not success:
  raise Exception('Tokenization does not match!'      )

 with torch.no_grad():
  if is_folding_model:
   # Let's test the model in parts
   # ESMFold always converts the ESM stem to float16, which requires float16 ops
   # that don't exist on CPU. Therefore, to test it we need to run it on GPU. However,
   # ESMFold is what we in the community call a "big boy" and so we desperately avoid putting both the
   # original and the converted model on the GPU at the same time.
   UpperCAmelCase			:      Union[str, Any]		   =					esm.cuda().infer([row[1] for row in sample_data]      )
   UpperCAmelCase			:      Optional[Any]		   =					model.cuda()(
       input_ids=hf_tokens['input_ids'].cuda()    ,			attention_mask=hf_tokens['attention_mask'].cuda()      )
  else:
   UpperCAmelCase			:      int		   =					model(**UpperCAmelCase_    ,			output_hidden_states=UpperCAmelCase_      )
   UpperCAmelCase			:      List[Any]		   =					our_output['logits']
   if classification_head:
    UpperCAmelCase			:      str		   =					esm.model.classification_heads['mnli'](esm.extract_features(UpperCAmelCase_      )      )
   else:
    UpperCAmelCase			:      Union[str, Any]		   =					esm(hf_tokens['input_ids']    ,			repr_layers=list(range(9_99      )      )      )
    UpperCAmelCase			:      Dict		   =					their_output['logits']

  if is_folding_model:
   UpperCAmelCase			:      Optional[Any]		   =					torch.max(torch.abs(our_output['positions'] - their_output['positions']      )      ).item()
   UpperCAmelCase			:      Tuple		   =					torch.allclose(our_output['positions']    ,			their_output['positions']    ,			atol=1E-5      )
  else:
   UpperCAmelCase			:      Dict		   =					torch.max(torch.abs(our_output - their_output      )      ).item()
   UpperCAmelCase			:      Optional[int]		   =					torch.allclose(UpperCAmelCase_    ,			UpperCAmelCase_    ,			atol=1E-5      )

  print(F"""max_absolute_diff = {max_absolute_diff}"""      )  # ~ 1e-5
  print('Do both models output the same tensors?'    ,			'🔥' if success else '💩'      )

  if not success:
   raise Exception('Something went wRoNg'      )

  if not is_folding_model:
   # Let's check contact prediction too
   UpperCAmelCase			:      List[Any]		   =					model.predict_contacts(hf_tokens['input_ids']    ,			hf_tokens['attention_mask']      )
   UpperCAmelCase			:      Tuple		   =					esm.predict_contacts(hf_tokens['input_ids']      )
   UpperCAmelCase			:      List[Any]		   =					torch.max(torch.abs(our_output - their_output      )      ).item()
   UpperCAmelCase			:      Any		   =					torch.allclose(UpperCAmelCase_    ,			UpperCAmelCase_    ,			atol=1E-5      )

   print('Contact prediction testing:'      )
   print(F"""max_absolute_diff = {max_absolute_diff}"""      )  # ~ 1e-5
   print('Do both models output the same tensors?'    ,			'🔥' if success else '💩'      )

   if not success:
    raise Exception('Something went wRoNg'      )

  pathlib.Path(UpperCAmelCase_      ).mkdir(parents=UpperCAmelCase_    ,			exist_ok=UpperCAmelCase_      )
  print(F"""Saving model to {pytorch_dump_folder_path}"""      )
  model.save_pretrained(UpperCAmelCase_      )

  del esm  # Free up some memory before continuing

 print(F"""Saving tokenizer to {pytorch_dump_folder_path}"""      )
 hf_tokenizer.save_pretrained(UpperCAmelCase_      )

 if push_to_repo:
  model.push_to_hub(repo_id=UpperCAmelCase_    ,			use_auth_token=UpperCAmelCase_      )
  hf_tokenizer.push_to_hub(repo_id=UpperCAmelCase_    ,			use_auth_token=UpperCAmelCase_      )


if __name__ == "__main__":
 lowercase__            =     argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--pytorch_dump_folder_path", type=str, required=True, help="Path to the output PyTorch model."
 )
 parser.add_argument(
     "--classification_head", action="store_true", help="Whether to convert a final classification head."
 )
 parser.add_argument("--model", default=None, type=str, required=True, help="Name of model to convert.")
 parser.add_argument("--push_to_repo", type=str, help="Repo to upload to (including username!).")
 parser.add_argument("--auth_token", type=str, help="HuggingFace auth token.")
 lowercase__            =     parser.parse_args()
 convert_esm_checkpoint_to_pytorch(
     args.model, args.pytorch_dump_folder_path, args.classification_head, args.push_to_repo, args.auth_token
 )







'''simple docstring'''

import sacrebleu as scb
from packaging import version

import datasets


lowercase__            =     "\\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

lowercase__            =     "\\nSacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.\nInspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text.\nIt also knows all the standard test sets and handles downloading, processing, and tokenization for you.\n\nSee the [README.md] file at https://github.com/mjpost/sacreBLEU for more information.\n"

lowercase__            =     "\nProduces BLEU scores along with its sufficient statistics\nfrom a source against one or more references.\n\nArgs:\n    predictions (`list` of `str`): list of translations to score. Each translation should be tokenized into a list of tokens.\n    references (`list` of `list` of `str`): A list of lists of references. The contents of the first sub-list are the references for the first prediction, the contents of the second sub-list are for the second prediction, etc. Note that there must be the same number of references for each prediction (i.e. all sub-lists must be of the same length).\n    smooth_method (`str`): The smoothing method to use, defaults to `'exp'`. Possible values are:\n        - `'none'`: no smoothing\n        - `'floor'`: increment zero counts\n        - `'add-k'`: increment num/denom by k for n>1\n        - `'exp'`: exponential decay\n    smooth_value (`float`): The smoothing value. Only valid when `smooth_method='floor'` (in which case `smooth_value` defaults to `0.1`) or `smooth_method='add-k'` (in which case `smooth_value` defaults to `1`).\n    tokenize (`str`): Tokenization method to use for BLEU. If not provided, defaults to `'zh'` for Chinese, `'ja-mecab'` for Japanese and `'13a'` (mteval) otherwise. Possible values are:\n        - `'none'`: No tokenization.\n        - `'zh'`: Chinese tokenization.\n        - `'13a'`: mimics the `mteval-v13a` script from Moses.\n        - `'intl'`: International tokenization, mimics the `mteval-v14` script from Moses\n        - `'char'`: Language-agnostic character-level tokenization.\n        - `'ja-mecab'`: Japanese tokenization. Uses the [MeCab tokenizer](https://pypi.org/project/mecab-python3).\n    lowercase (`bool`): If `True`, lowercases the input, enabling case-insensitivity. Defaults to `False`.\n    force (`bool`): If `True`, insists that your tokenized input is actually detokenized. Defaults to `False`.\n    use_effective_order (`bool`): If `True`, stops including n-gram orders for which precision is 0. This should be `True`, if sentence-level BLEU will be computed. Defaults to `False`.\n\nReturns:\n    'score': BLEU score,\n    'counts': Counts,\n    'totals': Totals,\n    'precisions': Precisions,\n    'bp': Brevity penalty,\n    'sys_len': predictions length,\n    'ref_len': reference length,\n\nExamples:\n\n    Example 1:\n        >>> predictions = [\"hello there general kenobi\", \"foo bar foobar\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"], [\"foo bar foobar\", \"foo bar foobar\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions, references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        100.0\n\n    Example 2:\n        >>> predictions = [\"hello there general kenobi\",\n        ...                 \"on our way to ankh morpork\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"],\n        ...                 [\"goodbye ankh morpork\", \"ankh morpork\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions,\n        ...                             references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        39.8\n"




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






     '''simple docstring'''



     def   UpperCAmelCase_			(						self					:	Tuple			)		->      Union[str, Any]:
      if version.parse(scb.__version__			) < version.parse('1.4.12'			):
       raise ImportWarning(
           'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'
           'You can install it with `pip install "sacrebleu>=1.4.12"`.'			)
      return datasets.MetricInfo(
          description=_DESCRIPTION	,     citation=_CITATION	,     homepage='https://github.com/mjpost/sacreBLEU'	,     inputs_description=_KWARGS_DESCRIPTION	,     features=datasets.Features(
              {
                  'predictions': datasets.Value('string'	,     id='sequence'			),
                  'references': datasets.Sequence(datasets.Value('string'	,     id='sequence'			)	,     id='references'			),
              }			)	,     codebase_urls=['https://github.com/mjpost/sacreBLEU']	,     reference_urls=[
              'https://github.com/mjpost/sacreBLEU',
              'https://en.wikipedia.org/wiki/BLEU',
              'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213',
          ]	,     )




     def   UpperCAmelCase_			(						self					:	Union[str, Any]	,     lowercase_					:	Union[str, Any]	,     lowercase_					:	int	,     lowercase_					:	List[Any]="exp"	,     lowercase_					:	Optional[int]=None	,     lowercase_					:	List[str]=False	,     lowercase_					:	Tuple=False	,     lowercase_					:	int=None	,     lowercase_					:	str=False	,     )		->      Dict:
      UpperCAmelCase			:      Union[str, Any]		   =					len(references[0]			)
      if any(len(lowercase_			) != references_per_prediction for refs in references			):
       raise ValueError('Sacrebleu requires the same number of references for each prediction'			)
      UpperCAmelCase			:      Optional[Any]		   =					[[refs[i] for refs in references] for i in range(lowercase_			)]
      UpperCAmelCase			:      List[Any]		   =					scb.corpus_bleu(
          lowercase_	,     lowercase_	,     smooth_method=lowercase_	,     smooth_value=lowercase_	,     force=lowercase_	,     lowercase=lowercase_	,     use_effective_order=lowercase_	,     **({'tokenize': tokenize} if tokenize else {})	,     )
      UpperCAmelCase			:      Union[str, Any]		   =					{
          'score': output.score,
          'counts': output.counts,
          'totals': output.totals,
          'precisions': output.precisions,
          'bp': output.bp,
          'sys_len': output.sys_len,
          'ref_len': output.ref_len,
      }
      return output_dict




