





'''simple docstring'''







import argparse
import os
import pathlib

import fairseq
import torch
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import (
    DataaVecTextConfig,
    DataaVecTextForMaskedLM,
    DataaVecTextForSequenceClassification,
    DataaVecTextModel,
)
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)

# IMPORTANT: In order for this script to run, please make sure to download the dictionary: `dict.txt` from wget https://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz
# File copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_text.py
from transformers.utils import logging


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


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

A						    =							'''Hello world! cécé herlolip'''

def 		SCREAMING_SNAKE_CASE      (					lowerCAmelCase__     :	str       ,  lowerCAmelCase__     :	str       ,  lowerCAmelCase__     :	bool)			->						Any:

     '''simple docstring'''




     _lowercase						, _lowercase							:      Dict  						=							os.path.split(lowerCAmelCase__)
     _lowercase							:      str  						=							DataaVecTextModel.from_pretrained(
         lowerCAmelCase__       ,  checkpoint_file=lowerCAmelCase__)
     dataavec.eval()  # disable dropout
     _lowercase							:      Dict  						=							dataavec.models[0]
     _lowercase							:      int  						=							dataavec_model.encoder.sentence_encoder
     _lowercase							:      int  						=							DataaVecTextConfig(
         vocab_size=dataavec_sent_encoder.embed_tokens.num_embeddings       ,  hidden_size=dataavec_model.args.encoder_embed_dim       ,  num_hidden_layers=dataavec_model.args.encoder_layers       ,  num_attention_heads=dataavec_model.args.encoder_attention_heads       ,  intermediate_size=dataavec_model.args.encoder_ffn_embed_dim       ,  max_position_embeddings=5_14       ,  type_vocab_size=1       ,  layer_norm_eps=1E-5       ,  )
     if classification_head:
          _lowercase							:      Optional[int]  						=							dataavec.model.classification_heads['mnli'].out_proj.weight.shape[0]
     print('Our BERT config:'       ,  lowerCAmelCase__)

     _lowercase							:      Any  						=							DataaVecTextForSequenceClassification(lowerCAmelCase__) if classification_head else DataaVecTextForMaskedLM(lowerCAmelCase__)
     model.eval()

     # Now let's copy all the weights.
     # Embeddings
     _lowercase							:      Tuple  						=							dataavec_sent_encoder.embed_tokens.weight
     _lowercase							:      Optional[int]  						=							dataavec_sent_encoder.embed_positions.weight
     _lowercase							:      Optional[int]  						=							torch.zeros_like(
         model.dataavec_text.embeddings.token_type_embeddings.weight)  # just zero them out b/c data2vec doesn't use them.
     _lowercase							:      List[str]  						=							dataavec_sent_encoder.layernorm_embedding.weight
     _lowercase							:      str  						=							dataavec_sent_encoder.layernorm_embedding.bias

     for i in range(config.num_hidden_layers):
          # Encoder: start of layer
          _lowercase							:      BertLayer  						=							model.dataavec_text.encoder.layer[i]
          _lowercase							:      TransformerSentenceEncoderLayer  						=							dataavec_sent_encoder.layers[i]

          # self attention
          _lowercase							:      BertSelfAttention  						=							layer.attention.self
          assert dataavec_layer.self_attn.k_proj.weight.data.shape == torch.Size(
              (config.hidden_size, config.hidden_size)), (
              "Shape for data2vec_layer.self_attn.k_proj.weight.data should be"
              F''' {torch.Size((config.hidden_size, config.hidden_size))}'''
          )
          assert dataavec_layer.self_attn.q_proj.weight.data.shape == torch.Size(
              (config.hidden_size, config.hidden_size)), (
              "Shape for data2vec_layer.self_attn.q_proj.weight.data should be"
              F''' {torch.Size((config.hidden_size, config.hidden_size))}'''
          )
          assert dataavec_layer.self_attn.v_proj.weight.data.shape == torch.Size(
              (config.hidden_size, config.hidden_size)), (
              "Shape for data2vec_layer.self_attn.v_proj.weight.data should be"
              F''' {torch.Size((config.hidden_size, config.hidden_size))}'''
          )

          _lowercase							:      Union[str, Any]  						=							dataavec_layer.self_attn.q_proj.weight
          _lowercase							:      Optional[int]  						=							dataavec_layer.self_attn.q_proj.bias
          _lowercase							:      Any  						=							dataavec_layer.self_attn.k_proj.weight
          _lowercase							:      Optional[Any]  						=							dataavec_layer.self_attn.k_proj.bias
          _lowercase							:      Union[str, Any]  						=							dataavec_layer.self_attn.v_proj.weight
          _lowercase							:      Any  						=							dataavec_layer.self_attn.v_proj.bias

          # self-attention output
          _lowercase							:      BertSelfOutput  						=							layer.attention.output
          assert (
              self_output.dense.weight.shape == dataavec_layer.self_attn.out_proj.weight.shape
          ), F'''Shape for self_output.dense.weight should be {dataavec_layer.self_attn.out_proj.weight.shape}'''
          _lowercase							:      Any  						=							dataavec_layer.self_attn.out_proj.weight
          _lowercase							:      Union[str, Any]  						=							dataavec_layer.self_attn.out_proj.bias
          _lowercase							:      Union[str, Any]  						=							dataavec_layer.self_attn_layer_norm.weight
          _lowercase							:      List[Any]  						=							dataavec_layer.self_attn_layer_norm.bias

          # intermediate
          _lowercase							:      BertIntermediate  						=							layer.intermediate
          assert (
              intermediate.dense.weight.shape == dataavec_layer.fca.weight.shape
          ), F'''Shape for intermediate.dense.weight should be {dataavec_layer.fca.weight.shape}'''
          _lowercase							:      Tuple  						=							dataavec_layer.fca.weight
          _lowercase							:      Optional[Any]  						=							dataavec_layer.fca.bias

          # output
          _lowercase							:      BertOutput  						=							layer.output
          assert (
              bert_output.dense.weight.shape == dataavec_layer.fca.weight.shape
          ), F'''Shape for bert_output.dense.weight should be {dataavec_layer.fca.weight.shape}'''
          _lowercase							:      List[str]  						=							dataavec_layer.fca.weight
          _lowercase							:      int  						=							dataavec_layer.fca.bias
          _lowercase							:      List[Any]  						=							dataavec_layer.final_layer_norm.weight
          _lowercase							:      Union[str, Any]  						=							dataavec_layer.final_layer_norm.bias
          # end of layer

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

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

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

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


if __name__ == "__main__":
    A						    =							argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        '''--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.'''
    )
    A						    =							parser.parse_args()
    convert_dataavec_checkpoint_to_pytorch(
        args.checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
    )






'''simple docstring'''







import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


A						    =							'''\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
'''

A						    =							'''
This metric wrap the official scoring script for version 2 of the Stanford Question
Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
'''

A						    =							'''
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer \'id\' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - \'id\': id of the question-answer pair (see above),
            - \'answers\': a list of Dict {\'text\': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    \'exact\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
    \'total\': Number of score considered
    \'HasAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'HasAns_f1\': The F-score of predicted tokens versus the gold answer
    \'HasAns_total\': Number of score considered
    \'NoAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'NoAns_f1\': The F-score of predicted tokens versus the gold answer
    \'NoAns_total\': Number of score considered
    \'best_exact\': Best exact match (with varying threshold)
    \'best_exact_thresh\': No-answer probability threshold associated to the best exact match
    \'best_f1\': Best F1 (with varying threshold)
    \'best_f1_thresh\': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\', \'no_answer_probability\': 0.}]
    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]
    >>> squad_v2_metric = datasets.load_metric("squad_v2")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact\': 100.0, \'f1\': 100.0, \'total\': 1, \'HasAns_exact\': 100.0, \'HasAns_f1\': 100.0, \'HasAns_total\': 1, \'best_exact\': 100.0, \'best_exact_thresh\': 0.0, \'best_f1\': 100.0, \'best_f1_thresh\': 0.0}
'''



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,   _KWARGS_DESCRIPTION      )
class 							__SCREAMING_SNAKE_CASE			(       datasets.Metric      ):
      '''simple docstring'''



      def   _lowerCamelCase		(							self    : Tuple  )		->  Dict:
           return datasets.MetricInfo(
               description=_DESCRIPTION   ,citation=_CITATION   ,inputs_description=_KWARGS_DESCRIPTION   ,features=datasets.Features(
                   {
                       'predictions': {
                           'id': datasets.Value('string'  ),
                           'prediction_text': datasets.Value('string'  ),
                           'no_answer_probability': datasets.Value('float32'  ),
                       },
                       'references': {
                           'id': datasets.Value('string'  ),
                           'answers': datasets.features.Sequence(
                               {'text': datasets.Value('string'  ), 'answer_start': datasets.Value('int32'  )}  ),
                       },
                   }  )   ,codebase_urls=['https://rajpurkar.github.io/SQuAD-explorer/']   ,reference_urls=['https://rajpurkar.github.io/SQuAD-explorer/']   ,)



      def   _lowerCamelCase		(							self    : Optional[int]   ,UpperCamelCase    : Optional[Any]   ,UpperCamelCase    : Any   ,UpperCamelCase    : int=1.0  )		->  Any:
           _lowercase							:      Optional[int]  						=							{p['id']: p['no_answer_probability'] for p in predictions}
           _lowercase							:      Union[str, Any]  						=							[{'paragraphs': [{'qas': references}]}]
           _lowercase							:      str  						=							{p['id']: p['prediction_text'] for p in predictions}

           _lowercase							:      Tuple  						=							make_qid_to_has_ans(UpperCamelCase  )  # maps qid to True/False
           _lowercase							:      Dict  						=							[k for k, v in qid_to_has_ans.items() if v]
           _lowercase							:      Tuple  						=							[k for k, v in qid_to_has_ans.items() if not v]

           _lowercase						, _lowercase							:      Tuple  						=							get_raw_scores(UpperCamelCase   ,UpperCamelCase  )
           _lowercase							:      Tuple  						=							apply_no_ans_threshold(UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase  )
           _lowercase							:      Union[str, Any]  						=							apply_no_ans_threshold(UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase  )
           _lowercase							:      Optional[int]  						=							make_eval_dict(UpperCamelCase   ,UpperCamelCase  )

           if has_ans_qids:
                _lowercase							:      Dict  						=							make_eval_dict(UpperCamelCase   ,UpperCamelCase   ,qid_list=UpperCamelCase  )
                merge_eval(UpperCamelCase   ,UpperCamelCase   ,'HasAns'  )
           if no_ans_qids:
                _lowercase							:      Tuple  						=							make_eval_dict(UpperCamelCase   ,UpperCamelCase   ,qid_list=UpperCamelCase  )
                merge_eval(UpperCamelCase   ,UpperCamelCase   ,'NoAns'  )
           find_all_best_thresh(UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase  )
           return dict(UpperCamelCase  )