


"""simple docstring"""

from scipy.stats import spearmanr

import datasets


UpperCAmelCase__					="\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n"

UpperCAmelCase__					="\nArgs:\n    predictions (`List[float]`): Predicted labels, as returned by a model.\n    references (`List[float]`): Ground truth labels.\n    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n            only the spearmanr score. Defaults to `False`.\nReturns:\n    spearmanr (`float`): Spearman correlation coefficient.\n    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n    Example 1:\n        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n        >>> print(results)\n        {'spearmanr': -0.7}\n\n    Example 2:\n        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n        ...                                     predictions=[10, 9, 2.5, 6, 4],\n        ...                                     return_pvalue=True)\n        >>> print(results['spearmanr'])\n        -0.7\n        >>> print(round(results['spearmanr_pvalue'], 2))\n        0.19\n"

UpperCAmelCase__					=R"\\n@book{kokoska2000crc,\n  title={CRC standard probability and statistics tables and formulae},\n  author={Kokoska, Stephen and Zwillinger, Daniel},\n  year={2000},\n  publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n            Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n            Kern, Robert and Larson, Eric and Carey, C J and\n            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and\n            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n            Harris, Charles R. and Archibald, Anne M. and\n            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and\n            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n            Computing in Python}},\n  journal = {Nature Methods},\n  year    = {2020},\n  volume  = {17},\n  pages   = {261--272},\n  adsurl  = {https://rdcu.be/b08Wh},\n  doi     = {10.1038/s41592-019-0686-2},\n}\n"





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      , _KWARGS_DESCRIPTION     )
class  lowerCamelCase__    (		datasets.Metric     ):
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict				):






       '''simple docstring'''


       return datasets.MetricInfo(
           description=_DESCRIPTION   ,							citation=_CITATION   ,							inputs_description=_KWARGS_DESCRIPTION   ,							features=datasets.Features(
               {
                   """predictions""": datasets.Value("""float"""				),
                   """references""": datasets.Value("""float"""				),
               }				)   ,							reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""]   ,							)






      def SCREAMING_SNAKE_CASE_						(		self						:						Union[str, Any]   ,							A_						:						int   ,							A_						:						Tuple   ,							A_						:						Union[str, Any]=False				):






       '''simple docstring'''


       __lowercase						=						spearmanr(A_   ,							A_				)
       if return_pvalue:
        return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
       else:
        return {"spearmanr": results[0]}




"""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__					=logging.getLogger(__name__)


UpperCAmelCase__					="Hello world! cécé herlolip"


UpperCAmelCase__					=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 lowerCAmelCase_   (					UpperCamelCase__						:			Tuple					, UpperCamelCase__						:			Union[str, Any]			):






 """simple docstring"""







 __lowercase						=						BertAbsConfig(
     temp_dir="""."""					, finetune_bert=UpperCamelCase__					, large=UpperCamelCase__					, share_emb=UpperCamelCase__					, use_bert_emb=UpperCamelCase__					, 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					, )
 __lowercase						=						torch.load(UpperCamelCase__					, lambda UpperCamelCase__					, UpperCamelCase__			: storage			)
 __lowercase						=						AbsSummarizer(UpperCamelCase__					, torch.device("""cpu"""			)					, UpperCamelCase__			)
 original.eval()

 __lowercase						=						BertAbsSummarizer(UpperCamelCase__					, 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"""			)
 __lowercase						=						BertTokenizer.from_pretrained("""bert-base-uncased"""			)

 # prepare the model inputs
 __lowercase						=						tokenizer.encode("""This is sample éàalj'-."""			)
 encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(UpperCamelCase__			))			)
 __lowercase						=						torch.tensor(UpperCamelCase__			).unsqueeze(0			)
 __lowercase						=						tokenizer.encode("""This is sample 3 éàalj'-."""			)
 decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(UpperCamelCase__			))			)
 __lowercase						=						torch.tensor(UpperCamelCase__			).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
 __lowercase						=						encoder_input_ids
 __lowercase						=						decoder_input_ids
 __lowercase						=						__lowercase						=						None
 __lowercase						=						None
 __lowercase						=						__lowercase						=						None
 __lowercase						=						__lowercase						=						None
 __lowercase						=						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
 __lowercase						=						original(UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__			)[0]
 __lowercase						=						original.generator(UpperCamelCase__			)

 __lowercase						=						new_model(
     UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__					, UpperCamelCase__			)[0]
 __lowercase						=						new_model.generator(UpperCamelCase__			)

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

 __lowercase						=						torch.allclose(UpperCamelCase__					, UpperCamelCase__					, 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__					=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__					=parser.parse_args()

       convert_bertabs_checkpoints(
           args.bertabs_checkpoint_path,
           args.pytorch_dump_folder_path,
       )
