






'''simple docstring'''




from scipy.stats import spearmanr

import datasets


__lowerCamelCase   :					str   							=					'''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''

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

    Example 2:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results[\'spearmanr\'])
        -0.7
        >>> print(round(results[\'spearmanr_pvalue\'], 2))
        0.19
'''

__lowerCamelCase   :					List[str]   							=					R'''\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@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, {\.I}lhan 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, Ant{\^o}nio 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    A_	(datasets.Metric							):
							"""simple docstring"""




							def 							_A	(		self			:str				)				->  Union[str, Any]:


										'''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 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:Optional[Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:Optional[Any]=False				)				->  List[Any]:


										'''simple docstring'''




										snake_case_				:					Optional[Any]   =       spearmanr(lowerCAmelCase__       ,							lowerCAmelCase__				)
										if return_pvalue:
													return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
										else:
													return {"spearmanr": results[0]}












'''simple docstring'''




import argparse
import pathlib

import fairseq
import torch
from fairseq.models.roberta import RobertaModel as FairseqRobertaModel
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.models.roberta.modeling_roberta import RobertaAttention
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''):
		raise Exception('''requires fairseq >= 1.0.0a''')

logging.set_verbosity_info()
__lowerCamelCase   :					Union[str, Any]   							=					logging.get_logger(__name__)

__lowerCamelCase   :					Union[str, Any]   							=					'''Hello world! cécé herlolip'''

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__     ,__magic_name__						)->    Optional[Any]:



			"""simple docstring"""



			snake_case_				:					str   =       FairseqRobertaModel.from_pretrained(__magic_name__						)
			roberta.eval()  # disable dropout
			snake_case_				:					Dict   =       roberta.model.encoder.sentence_encoder
			snake_case_				:					List[str]   =       XLMRobertaConfig(
			    vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings     ,hidden_size=roberta.cfg.model.encoder_embed_dim     ,num_hidden_layers=roberta.cfg.model.encoder_layers     ,num_attention_heads=roberta.cfg.model.encoder_attention_heads     ,intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim     ,max_position_embeddings=514     ,type_vocab_size=1     ,layer_norm_eps=1E-5     ,)
			if classification_head:
						snake_case_				:					List[str]   =       roberta.model.classification_heads["mnli"].out_proj.weight.shape[0]

			print("Our RoBERTa config:"     ,__magic_name__						)

			snake_case_				:					List[str]   =       XLMRobertaXLForSequenceClassification(__magic_name__						) if classification_head else XLMRobertaXLForMaskedLM(__magic_name__						)
			model.eval()

			# Now let's copy all the weights.
			# Embeddings
			snake_case_				:					List[Any]   =       roberta_sent_encoder.embed_tokens.weight
			snake_case_				:					int   =       roberta_sent_encoder.embed_positions.weight
			snake_case_				:					Union[str, Any]   =       torch.zeros_like(
			    model.roberta.embeddings.token_type_embeddings.weight						)  # just zero them out b/c RoBERTa doesn't use them.

			snake_case_				:					Union[str, Any]   =       roberta_sent_encoder.layer_norm.weight
			snake_case_				:					str   =       roberta_sent_encoder.layer_norm.bias

			for i in range(config.num_hidden_layers						):
						# Encoder: start of layer
						snake_case_				:					BertLayer   =       model.roberta.encoder.layer[i]
						snake_case_				:					TransformerSentenceEncoderLayer   =       roberta_sent_encoder.layers[i]

						snake_case_				:					RobertaAttention   =       layer.attention
						snake_case_				:					Dict   =       roberta_layer.self_attn_layer_norm.weight
						snake_case_				:					Dict   =       roberta_layer.self_attn_layer_norm.bias

						# self attention
						snake_case_				:					BertSelfAttention   =       layer.attention.self
						assert (
						    roberta_layer.self_attn.k_proj.weight.data.shape
						    == roberta_layer.self_attn.q_proj.weight.data.shape
						    == roberta_layer.self_attn.v_proj.weight.data.shape
						    == torch.Size((config.hidden_size, config.hidden_size)						)
						)

						snake_case_				:					Dict   =       roberta_layer.self_attn.q_proj.weight
						snake_case_				:					Any   =       roberta_layer.self_attn.q_proj.bias
						snake_case_				:					Optional[Any]   =       roberta_layer.self_attn.k_proj.weight
						snake_case_				:					Optional[Any]   =       roberta_layer.self_attn.k_proj.bias
						snake_case_				:					Optional[int]   =       roberta_layer.self_attn.v_proj.weight
						snake_case_				:					Any   =       roberta_layer.self_attn.v_proj.bias

						# self-attention output
						snake_case_				:					BertSelfOutput   =       layer.attention.output
						assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
						snake_case_				:					List[str]   =       roberta_layer.self_attn.out_proj.weight
						snake_case_				:					Optional[int]   =       roberta_layer.self_attn.out_proj.bias

						# this one is final layer norm
						snake_case_				:					int   =       roberta_layer.final_layer_norm.weight
						snake_case_				:					Union[str, Any]   =       roberta_layer.final_layer_norm.bias

						# intermediate
						snake_case_				:					BertIntermediate   =       layer.intermediate
						assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
						snake_case_				:					List[str]   =       roberta_layer.fca.weight
						snake_case_				:					List[Any]   =       roberta_layer.fca.bias

						# output
						snake_case_				:					BertOutput   =       layer.output
						assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
						snake_case_				:					Any   =       roberta_layer.fca.weight
						snake_case_				:					Any   =       roberta_layer.fca.bias
						# end of layer

			if classification_head:
						snake_case_				:					int   =       roberta.model.classification_heads["mnli"].dense.weight
						snake_case_				:					Union[str, Any]   =       roberta.model.classification_heads["mnli"].dense.bias
						snake_case_				:					Tuple   =       roberta.model.classification_heads["mnli"].out_proj.weight
						snake_case_				:					str   =       roberta.model.classification_heads["mnli"].out_proj.bias
			else:
						# LM Head
						snake_case_				:					Optional[Any]   =       roberta.model.encoder.lm_head.dense.weight
						snake_case_				:					int   =       roberta.model.encoder.lm_head.dense.bias
						snake_case_				:					Optional[Any]   =       roberta.model.encoder.lm_head.layer_norm.weight
						snake_case_				:					Optional[int]   =       roberta.model.encoder.lm_head.layer_norm.bias
						snake_case_				:					int   =       roberta.model.encoder.lm_head.weight
						snake_case_				:					List[str]   =       roberta.model.encoder.lm_head.bias

			# Let's check that we get the same results.
			snake_case_				:					torch.Tensor   =       roberta.encode(__magic_name__						).unsqueeze(0						)  # batch of size 1

			snake_case_				:					Union[str, Any]   =       model(__magic_name__						)[0]
			if classification_head:
						snake_case_				:					Optional[Any]   =       roberta.model.classification_heads["mnli"](roberta.extract_features(__magic_name__						)						)
			else:
						snake_case_				:					List[str]   =       roberta.model(__magic_name__						)[0]
			print(our_output.shape     ,their_output.shape						)
			snake_case_				:					str   =       torch.max(torch.abs(our_output - their_output						)						).item()
			print(F'''max_absolute_diff = {max_absolute_diff}'''						)  # ~ 1e-7
			snake_case_				:					Any   =       torch.allclose(__magic_name__     ,__magic_name__     ,atol=1E-3						)
			print("Do both models output the same tensors?"     ,"🔥" if success else "💩"						)
			if not success:
						raise Exception("Something went wRoNg"						)

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


if __name__ == "__main__":
		__lowerCamelCase   :					Any   							=					argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '''--roberta_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.'''
		)
		parser.add_argument(
		    '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.'''
		)
		__lowerCamelCase   :					Tuple   							=					parser.parse_args()
		convert_xlm_roberta_xl_checkpoint_to_pytorch(
		    args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
		)




