

'''simple docstring'''



import argparse
import logging
from collections import namedtuple

import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer  # The authors' implementation

from transformers import BertTokenizer


logging.basicConfig(level=logging.INFO)
_UpperCamelCase						:  Optional[Any]							       =				logging.getLogger(__name__)


_UpperCamelCase						:  List[Any]							       =				"Hello world! cécé herlolip"


_UpperCamelCase						:  int							       =				namedtuple(
    "BertAbsConfig",
    [
        "temp_dir",
        "large",
        "use_bert_emb",
        "finetune_bert",
        "encoder",
        "share_emb",
        "max_pos",
        "enc_layers",
        "enc_hidden_size",
        "enc_heads",
        "enc_ff_size",
        "enc_dropout",
        "dec_layers",
        "dec_hidden_size",
        "dec_heads",
        "dec_ff_size",
        "dec_dropout",
    ],
)


def       snake_case   (	snake_case      : int					,		snake_case      : Optional[Any]			) ->  Optional[Any]:


    """simple docstring"""


    lowerCAmelCase 						=							BertAbsConfig(
        temp_dir='.'					,		finetune_bert=snake_case					,		large=snake_case					,		share_emb=snake_case					,		use_bert_emb=snake_case					,		encoder='bert'					,		max_pos=512					,		enc_layers=6					,		enc_hidden_size=512					,		enc_heads=8					,		enc_ff_size=512					,		enc_dropout=0.2					,		dec_layers=6					,		dec_hidden_size=768					,		dec_heads=8					,		dec_ff_size=2048					,		dec_dropout=0.2					,		)
    lowerCAmelCase 						=							torch.load(snake_case					,		lambda snake_case					,		snake_case			: storage			)
    lowerCAmelCase 						=							AbsSummarizer(snake_case					,		torch.device('cpu'			)					,		snake_case			)
    original.eval()

    lowerCAmelCase 						=							BertAbsSummarizer(snake_case					,		torch.device('cpu'			)			)
    new_model.eval()

    # -------------------
    # Convert the weights
    # -------------------

    logging.info('convert the model'			)
    new_model.bert.load_state_dict(original.bert.state_dict()			)
    new_model.decoder.load_state_dict(original.decoder.state_dict()			)
    new_model.generator.load_state_dict(original.generator.state_dict()			)

    # ----------------------------------
    # Make sure the outpus are identical
    # ----------------------------------

    logging.info('Make sure that the models\' outputs are identical'			)
    lowerCAmelCase 						=							BertTokenizer.from_pretrained('bert-base-uncased'			)

    # prepare the model inputs
    lowerCAmelCase 						=							tokenizer.encode('This is sample éàalj\'-.'			)
    encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(snake_case			))			)
    lowerCAmelCase 						=							torch.tensor(snake_case			).unsqueeze(0			)
    lowerCAmelCase 						=							tokenizer.encode('This is sample 3 éàalj\'-.'			)
    decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(snake_case			))			)
    lowerCAmelCase 						=							torch.tensor(snake_case			).unsqueeze(0			)

    # failsafe to make sure the weights reset does not affect the
    # loaded weights.
    assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight			)			) == 0

    # forward pass
    lowerCAmelCase 						=							encoder_input_ids
    lowerCAmelCase 						=							decoder_input_ids
    lowerCAmelCase 						=							lowerCAmelCase 						=							None
    lowerCAmelCase 						=							None
    lowerCAmelCase 						=							lowerCAmelCase 						=							None
    lowerCAmelCase 						=							lowerCAmelCase 						=							None
    lowerCAmelCase 						=							None

    # The original model does not apply the geneator layer immediatly but rather in
    # the beam search (where it combines softmax + linear layer). Since we already
    # apply the softmax in our generation process we only apply the linear layer here.
    # We make sure that the outputs of the full stack are identical
    lowerCAmelCase 						=							original(snake_case					,		snake_case					,		snake_case					,		snake_case					,		snake_case					,		snake_case					,		snake_case			)[0]
    lowerCAmelCase 						=							original.generator(snake_case			)

    lowerCAmelCase 						=							new_model(
        snake_case					,		snake_case					,		snake_case					,		snake_case					,		snake_case			)[0]
    lowerCAmelCase 						=							new_model.generator(snake_case			)

    lowerCAmelCase 						=							torch.max(torch.abs(output_converted_model - output_original_model			)			).item()
    print('Maximum absolute difference beween weights: {:.2f}'.format(snake_case			)			)
    lowerCAmelCase 						=							torch.max(torch.abs(output_converted_generator - output_original_generator			)			).item()
    print('Maximum absolute difference beween weights: {:.2f}'.format(snake_case			)			)

    lowerCAmelCase 						=							torch.allclose(snake_case					,		snake_case					,		atol=1e-3			)
    if are_identical:
        logging.info('all weights are equal up to 1e-3'			)
    else:
        raise ValueError('the weights are different. The new model is likely different from the original one.'			)

    # The model has been saved with torch.save(model) and this is bound to the exact
    # directory structure. We save the state_dict instead.
    logging.info('saving the model\'s state dictionary'			)
    torch.save(
        new_model.state_dict()					,		'./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin'			)


if __name__ == "__main__":
     _UpperCamelCase						:  List[str]							       =				argparse.ArgumentParser()
     parser.add_argument(
         "--bertabs_checkpoint_path",
         default=None,
         type=str,
         required=True,
         help="Path the official PyTorch dump.",
     )
     parser.add_argument(
         "--pytorch_dump_folder_path",
         default=None,
         type=str,
         required=True,
         help="Path to the output PyTorch model.",
     )
     _UpperCamelCase						:  Optional[int]							       =				parser.parse_args()

     convert_bertabs_checkpoints(
         args.bertabs_checkpoint_path,
         args.pytorch_dump_folder_path,
     )








'''simple docstring'''



import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


_UpperCamelCase						:  Optional[Any]							       =				"\\n@inproceedings{snover-etal-2006-study,\n    title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n    author = \"Snover, Matthew  and\n      Dorr, Bonnie  and\n      Schwartz, Rich  and\n      Micciulla, Linnea  and\n      Makhoul, John\",\n    booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n    month = aug # \" 8-12\",\n    year = \"2006\",\n    address = \"Cambridge, Massachusetts, USA\",\n    publisher = \"Association for Machine Translation in the Americas\",\n    url = \"https://aclanthology.org/2006.amta-papers.25\",\n    pages = \"223--231\",\n}\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"

_UpperCamelCase						:  Any							       =				"\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n"

_UpperCamelCase						:  Dict							       =				"\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n    predictions (list of str): The system stream (a sequence of segments).\n    references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n                                    Only applies if `normalized = True`. Defaults to `False`.\n    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n    'score' (float): TER score (num_edits / sum_ref_lengths * 100)\n    'num_edits' (int): The cumulative number of edits\n    'ref_length' (float): The cumulative average reference length\n\nExamples:\n    Example 1:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\",\n        ...                     \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\n\n    Example 2:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\n\n    Example 3:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         normalized=True,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\n\n    Example 4:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\n\n    Example 5:\n        >>> predictions = [\"does this sentence match??\",\n        ...                    \"what about this sentence?\",\n        ...                    \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\n"



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

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      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='http://www.cs.umd.edu/~snover/tercom/'      , 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#ter']      , reference_urls=[
              'https://github.com/jhclark/tercom',
          ]      , )


  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE = False      , _SCREAMING_SNAKE_CASE = False      , _SCREAMING_SNAKE_CASE = False      , _SCREAMING_SNAKE_CASE = False      , ):





      '''simple docstring'''

      lowerCAmelCase 						=							len(references[0]	)
      if any(len(_SCREAMING_SNAKE_CASE	) != references_per_prediction for refs in references	):
          raise ValueError('Sacrebleu requires the same number of references for each prediction'	)
      lowerCAmelCase 						=							[[refs[i] for refs in references] for i in range(_SCREAMING_SNAKE_CASE	)]

      lowerCAmelCase 						=							TER(
          normalized=_SCREAMING_SNAKE_CASE      , no_punct=_SCREAMING_SNAKE_CASE      , asian_support=_SCREAMING_SNAKE_CASE      , case_sensitive=_SCREAMING_SNAKE_CASE      , )
      lowerCAmelCase 						=							sb_ter.corpus_score(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)

      return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}





