




'''simple docstring'''


import argparse
import json
import os

import torch

from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer
from transformers.tokenization_utils_base import AddedToken


@torch.no_grad()
def     SCREAMING_SNAKE_CASE							(   a_						:				int					,       a_						:				Optional[Any]					,       a_						:				Dict					,       a_						:				Tuple					,       a_						:				Tuple      ):
  # Load configuration defined in the metadata file
  with open(__lowerCAmelCase      ) as metadata_file:
    __a								=       json.load(__lowerCAmelCase      )
  __a								=       LukeConfig(use_entity_aware_attention=__lowerCAmelCase					,       **metadata['model_config']      )

  # Load in the weights from the checkpoint_path
  __a								=       torch.load(__lowerCAmelCase					,       map_location='cpu'      )

  # Load the entity vocab file
  __a								=       load_entity_vocab(__lowerCAmelCase      )

  __a								=       RobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name']      )

  # Add special tokens to the token vocabulary for downstream tasks
  __a								=       AddedToken('<ent>'					,       lstrip=__lowerCAmelCase					,       rstrip=__lowerCAmelCase      )
  __a								=       AddedToken('<ent2>'					,       lstrip=__lowerCAmelCase					,       rstrip=__lowerCAmelCase      )
  tokenizer.add_special_tokens({'additional_special_tokens': [entity_token_a, entity_token_a]}      )
  config.vocab_size += 2

  print(f"Saving tokenizer to {pytorch_dump_folder_path}"      )
  tokenizer.save_pretrained(__lowerCAmelCase      )
  with open(os.path.join(__lowerCAmelCase					,       LukeTokenizer.vocab_files_names['entity_vocab_file']      )					,       'w'      ) as f:
    json.dump(__lowerCAmelCase					,       __lowerCAmelCase      )

  __a								=       LukeTokenizer.from_pretrained(__lowerCAmelCase      )

  # Initialize the embeddings of the special tokens
  __a								=       state_dict['embeddings.word_embeddings.weight']
  __a								=       word_emb[tokenizer.convert_tokens_to_ids(['@']      )[0]].unsqueeze(0      )
  __a								=       word_emb[tokenizer.convert_tokens_to_ids(['#']      )[0]].unsqueeze(0      )
  __a								=       torch.cat([word_emb, ent_emb, enta_emb]      )

  # Initialize the query layers of the entity-aware self-attention mechanism
  for layer_index in range(config.num_hidden_layers      ):
    for matrix_name in ["query.weight", "query.bias"]:
      __a								=       f"encoder.layer.{layer_index}.attention.self."
      __a								=       state_dict[prefix + matrix_name]
      __a								=       state_dict[prefix + matrix_name]
      __a								=       state_dict[prefix + matrix_name]

    # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
  __a								=       state_dict['entity_embeddings.entity_embeddings.weight']
  __a								=       entity_emb[entity_vocab['[MASK]']]

  __a								=       LukeModel(config=__lowerCAmelCase      ).eval()

  __a						,							__a								=       model.load_state_dict(__lowerCAmelCase					,       strict=__lowerCAmelCase      )
  if not (len(__lowerCAmelCase      ) == 1 and missing_keys[0] == "embeddings.position_ids"):
    raise ValueError(f"Missing keys {', '.join(__lowerCAmelCase      )}. Expected only missing embeddings.position_ids"      )
  if not (all(key.startswith('entity_predictions'      ) or key.startswith('lm_head'      ) for key in unexpected_keys      )):
    raise ValueError(
        'Unexpected keys'
        f" {', '.join([key for key in unexpected_keys if not (key.startswith('entity_predictions'      ) or key.startswith('lm_head'      ))]      )}"      )

  # Check outputs
  __a								=       LukeTokenizer.from_pretrained(__lowerCAmelCase					,       task='entity_classification'      )

  __a								=       (
      'Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the'
      ' new world number one avoid a humiliating second- round exit at Wimbledon .'
  )
  __a								=       (39, 42)
  __a								=       tokenizer(__lowerCAmelCase					,       entity_spans=[span]					,       add_prefix_space=__lowerCAmelCase					,       return_tensors='pt'      )

  __a								=       model(**__lowerCAmelCase      )

  # Verify word hidden states
  if model_size == "large":
    __a								=       torch.Size((1, 42, 1024)      )
    __a								=       torch.tensor(
        [[0.01_33, 0.08_65, 0.00_95], [0.30_93, -0.25_76, -0.74_18], [-0.17_20, -0.21_17, -0.28_69]]      )
  else:  # base
    __a								=       torch.Size((1, 42, 768)      )
    __a								=       torch.tensor([[0.00_37, 0.13_68, -0.00_91], [0.10_99, 0.33_29, -0.10_95], [0.07_65, 0.53_35, 0.11_79]]      )

  if not (outputs.last_hidden_state.shape == expected_shape):
    raise ValueError(
        f"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}"      )
  if not torch.allclose(outputs.last_hidden_state[0, :3, :3]					,       __lowerCAmelCase					,       atol=1e-4      ):
    raise ValueError

  # Verify entity hidden states
  if model_size == "large":
    __a								=       torch.Size((1, 1, 1024)      )
    __a								=       torch.tensor([[0.04_66, -0.01_06, -0.01_79]]      )
  else:  # base
    __a								=       torch.Size((1, 1, 768)      )
    __a								=       torch.tensor([[0.14_57, 0.10_44, 0.01_74]]      )

  if not (outputs.entity_last_hidden_state.shape != expected_shape):
    raise ValueError(
        f"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is"
        f" {expected_shape}"      )
  if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3]					,       __lowerCAmelCase					,       atol=1e-4      ):
    raise ValueError

  # Finally, save our PyTorch model and tokenizer
  print('Saving PyTorch model to {}'.format(__lowerCAmelCase      )      )
  model.save_pretrained(__lowerCAmelCase      )


def     SCREAMING_SNAKE_CASE							(   a_						:				Any      ):
  __a								=       {}
  with open(__lowerCAmelCase					,       'r'					,       encoding='utf-8'      ) as f:
    for index, line in enumerate(__lowerCAmelCase      ):
      __a						,							__a								=       line.rstrip().split('\t'      )
      __a								=       index

  return entity_vocab


if __name__ == "__main__":
  UpperCAmelCase_					=   argparse.ArgumentParser()
  # Required parameters
  parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.")
  parser.add_argument(
      "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration."
  )
  parser.add_argument(
      "--entity_vocab_path",
      default=None,
      type=str,
      help="Path to an entity_vocab.tsv file, containing the entity vocabulary.",
  )
  parser.add_argument(
      "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model."
  )
  parser.add_argument(
      "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted."
  )
  UpperCAmelCase_					=   parser.parse_args()
  convert_luke_checkpoint(
      args.checkpoint_path,
      args.metadata_path,
      args.entity_vocab_path,
      args.pytorch_dump_folder_path,
      args.model_size,
  )









from scipy.stats import pearsonr

import datasets


__magic_name__  :  Union[str, Any]					=       """
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""


__magic_name__  :  Tuple					=       """
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results['pearsonr'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        ['p-value', 'pearsonr']
        >>> print(round(results['pearsonr'], 2))
        -0.74
        >>> print(round(results['p-value'], 2))
        0.15
"""


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





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,					_KWARGS_DESCRIPTION			)
class     SCREAMING_SNAKE_CASE__		(datasets.Metric			):
     def        A__      (						self	:		List[str]						):



       """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.pearsonr.html''']       ,						)



     def        A__      (						self	:		Any       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		Tuple       ,						__lowerCamelCase	:		Dict=False						):



       """simple docstring"""
       if return_pvalue:
         lowerCAmelCase__										=      pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)
         return {"pearsonr": results[0], "p-value": results[1]}
       else:
         return {"pearsonr": float(pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)[0]						)}

