

"""simple docstring"""




import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


__UpperCAmelCase			=					logging.get_logger(__name__)

__UpperCAmelCase			=					list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__UpperCAmelCase			=					tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class   __lowercase      :
  snake_case_												=							field(
      default=__lowerCamelCase						,      metadata={"""help""": """Model type selected in the list: """ + """, """.join(__lowerCamelCase       )}       )
  snake_case_												=							field(
      default=__lowerCamelCase						,      metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}       )
  snake_case_												=							field(
      default=1_2_8						,      metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }						,      )
  snake_case_												=							field(
      default=1_2_8						,      metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}						,      )
  snake_case_												=							field(
      default=6_4						,      metadata={
          """help""": (
              """The maximum number of tokens for the question. Questions longer than this will """
              """be truncated to this length."""
          )
      }						,      )
  snake_case_												=							field(
      default=3_0						,      metadata={
          """help""": (
              """The maximum length of an answer that can be generated. This is needed because the start """
              """and end predictions are not conditioned on one another."""
          )
      }						,      )
  snake_case_												=							field(
      default=__lowerCamelCase						,      metadata={"""help""": """Overwrite the cached training and evaluation sets"""}       )
  snake_case_												=							field(
      default=__lowerCamelCase						,      metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}       )
  snake_case_												=							field(
      default=0.0						,      metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  snake_case_												=							field(
      default=2_0						,      metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  snake_case_												=							field(
      default=0						,      metadata={
          """help""": (
              """language id of input for language-specific xlm models (see"""
              """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
          )
      }						,      )
  snake_case_												=							field(default=1						,      metadata={"""help""": """multiple threads for converting example to features"""}       )







class   __lowercase      (     __lowerCamelCase       ):
  snake_case_												=							"""train"""
  snake_case_												=							"""dev"""







class   __lowercase      (     __lowerCamelCase       ):
  snake_case_												=							42
  snake_case_												=							42
  snake_case_												=							42
  snake_case_												=							42

  def __init__(	self		:      List[str]       ,A		:      SquadDataTrainingArguments       ,A		:      PreTrainedTokenizer       ,A		:      Optional[int] = None       ,A		:      Union[str, Split] = Split.train       ,A		:      Optional[bool] = False       ,A		:      Optional[str] = None       ,A		:      Optional[str] = "pt"       ,):






   '''simple docstring'''
   UpperCAmelCase__       :	Dict        =       args
   UpperCAmelCase__       :	Optional[Any]        =       is_language_sensitive
   UpperCAmelCase__       :	str        =       SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
   if isinstance(A       ,A     ):
    try:
     UpperCAmelCase__       :	int        =       Split[mode]
    except KeyError:
     raise KeyError("""mode is not a valid split name"""     )
   UpperCAmelCase__       :	List[Any]        =       mode
   # Load data features from cache or dataset file
   UpperCAmelCase__       :	str        =       """v2""" if args.version_2_with_negative else """v1"""
   UpperCAmelCase__       :	List[str]        =       os.path.join(
       cache_dir if cache_dir is not None else args.data_dir       ,f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"       ,)

   # Make sure only the first process in distributed training processes the dataset,
   # and the others will use the cache.
   UpperCAmelCase__       :	int        =       cached_features_file + """.lock"""
   with FileLock(A     ):
    if os.path.exists(A     ) and not args.overwrite_cache:
     UpperCAmelCase__       :	Optional[Any]        =       time.time()
     UpperCAmelCase__       :	List[Any]        =       torch.load(A     )

     # Legacy cache files have only features, while new cache files
     # will have dataset and examples also.
     UpperCAmelCase__       :	Any        =       self.old_features["""features"""]
     UpperCAmelCase__       :	Tuple        =       self.old_features.get("""dataset"""       ,A     )
     UpperCAmelCase__       :	Tuple        =       self.old_features.get("""examples"""       ,A     )
     logger.info(
         f"Loading features from cached file {cached_features_file} [took %.3f s]"       ,time.time() - start     )

     if self.dataset is None or self.examples is None:
      logger.warning(
          f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"
          """ future run"""     )
    else:
     if mode == Split.dev:
      UpperCAmelCase__       :	Tuple        =       self.processor.get_dev_examples(args.data_dir     )
     else:
      UpperCAmelCase__       :	Dict        =       self.processor.get_train_examples(args.data_dir     )

     UpperCAmelCase__ ,   UpperCAmelCase__       :	List[str]        =       squad_convert_examples_to_features(
         examples=self.examples       ,tokenizer=A       ,max_seq_length=args.max_seq_length       ,doc_stride=args.doc_stride       ,max_query_length=args.max_query_length       ,is_training=mode == Split.train       ,threads=args.threads       ,return_dataset=A       ,)

     UpperCAmelCase__       :	str        =       time.time()
     torch.save(
         {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples}       ,A       ,)
     # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
     logger.info(
         f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"     )

  def __len__(	self		:      List[Any]     ):






   '''simple docstring'''
   return len(self.features     )




  def __getitem__(	self		:      str       ,A		:      List[Any]     ):






   '''simple docstring'''
   # Convert to Tensors and build dataset
   UpperCAmelCase__       :	Optional[Any]        =       self.features[i]

   UpperCAmelCase__       :	Any        =       torch.tensor(feature.input_ids       ,dtype=torch.long     )
   UpperCAmelCase__       :	int        =       torch.tensor(feature.attention_mask       ,dtype=torch.long     )
   UpperCAmelCase__       :	Tuple        =       torch.tensor(feature.token_type_ids       ,dtype=torch.long     )
   UpperCAmelCase__       :	List[Any]        =       torch.tensor(feature.cls_index       ,dtype=torch.long     )
   UpperCAmelCase__       :	Optional[int]        =       torch.tensor(feature.p_mask       ,dtype=torch.float     )
   UpperCAmelCase__       :	Optional[int]        =       torch.tensor(feature.is_impossible       ,dtype=torch.float     )

   UpperCAmelCase__       :	List[str]        =       {
       """input_ids""": input_ids,
       """attention_mask""": attention_mask,
       """token_type_ids""": token_type_ids,
   }

   if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
    del inputs["token_type_ids"]

   if self.args.model_type in ["xlnet", "xlm"]:
    inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask}     )
    if self.args.version_2_with_negative:
     inputs.update({"""is_impossible""": is_impossible}     )
    if self.is_language_sensitive:
     inputs.update({"""langs""": (torch.ones(input_ids.shape       ,dtype=torch.intaa     ) * self.args.lang_id)}     )

   if self.mode == Split.train:
    UpperCAmelCase__       :	Union[str, Any]        =       torch.tensor(feature.start_position       ,dtype=torch.long     )
    UpperCAmelCase__       :	Dict        =       torch.tensor(feature.end_position       ,dtype=torch.long     )
    inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions}     )

   return inputs











import argparse
import os

import gluonnlp as nlp
import mxnet as mx
import numpy as np
import torch
from gluonnlp.base import get_home_dir
from gluonnlp.model.bert import BERTEncoder
from gluonnlp.model.utils import _load_vocab
from gluonnlp.vocab import Vocab
from packaging import version
from torch import nn

from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.utils import logging


if version.parse(nlp.__version__) != version.parse("""0.8.3"""):
      raise Exception("""requires gluonnlp == 0.8.3""")

if version.parse(mx.__version__) != version.parse("""1.5.0"""):
      raise Exception("""requires mxnet == 1.5.0""")

logging.set_verbosity_info()
__magic_name__  :  Tuple					=       logging.get_logger(__name__)

__magic_name__  :  Optional[Any]					=       """The Nymphenburg Palace is a beautiful palace in Munich!"""
def 		a_							( __lowerCAmelCase   , __lowerCAmelCase				):
  lowerCAmelCase__										=      {
      '''attention_cell''': '''multi_head''',
      '''num_layers''': 4,
      '''units''': 10_24,
      '''hidden_size''': 7_68,
      '''max_length''': 5_12,
      '''num_heads''': 8,
      '''scaled''': True,
      '''dropout''': 0.1,
      '''use_residual''': True,
      '''embed_size''': 10_24,
      '''embed_dropout''': 0.1,
      '''word_embed''': None,
      '''layer_norm_eps''': 1E-5,
      '''token_type_vocab_size''': 2,
  }

  lowerCAmelCase__										=      bort_4_8_768_1024_hparams

  # Let's construct the original Bort model here
  # Taken from official BERT implementation, see:
  # https://github.com/alexa/bort/blob/master/bort/bort.py
  lowerCAmelCase__										=      BERTEncoder(
      attention_cell=predefined_args['''attention_cell''']   , num_layers=predefined_args['''num_layers''']   , units=predefined_args['''units''']   , hidden_size=predefined_args['''hidden_size''']   , max_length=predefined_args['''max_length''']   , num_heads=predefined_args['''num_heads''']   , scaled=predefined_args['''scaled''']   , dropout=predefined_args['''dropout''']   , output_attention=__lowerCAmelCase   , output_all_encodings=__lowerCAmelCase   , use_residual=predefined_args['''use_residual''']   , activation=predefined_args.get('''activation'''   , '''gelu'''				)   , layer_norm_eps=predefined_args.get('''layer_norm_eps'''   , __lowerCAmelCase				)   , )

  # Vocab information needs to be fetched first
  # It's the same as RoBERTa, so RobertaTokenizer can be used later
  lowerCAmelCase__										=      '''openwebtext_ccnews_stories_books_cased'''

  # Specify download folder to Gluonnlp's vocab
  lowerCAmelCase__										=      os.path.join(get_home_dir()   , '''models'''				)
  lowerCAmelCase__										=      _load_vocab(__lowerCAmelCase   , __lowerCAmelCase   , __lowerCAmelCase   , cls=__lowerCAmelCase				)

  lowerCAmelCase__										=      nlp.model.BERTModel(
      __lowerCAmelCase   , len(__lowerCAmelCase				)   , units=predefined_args['''units''']   , embed_size=predefined_args['''embed_size''']   , embed_dropout=predefined_args['''embed_dropout''']   , word_embed=predefined_args['''word_embed''']   , use_pooler=__lowerCAmelCase   , use_token_type_embed=__lowerCAmelCase   , token_type_vocab_size=predefined_args['''token_type_vocab_size''']   , use_classifier=__lowerCAmelCase   , use_decoder=__lowerCAmelCase   , )

  original_bort.load_parameters(__lowerCAmelCase   , cast_dtype=__lowerCAmelCase   , ignore_extra=__lowerCAmelCase				)
  lowerCAmelCase__										=      original_bort._collect_params_with_prefix()

  # Build our config 🤗
  lowerCAmelCase__										=      {
      '''architectures''': ['''BertForMaskedLM'''],
      '''attention_probs_dropout_prob''': predefined_args['''dropout'''],
      '''hidden_act''': '''gelu''',
      '''hidden_dropout_prob''': predefined_args['''dropout'''],
      '''hidden_size''': predefined_args['''embed_size'''],
      '''initializer_range''': 0.02,
      '''intermediate_size''': predefined_args['''hidden_size'''],
      '''layer_norm_eps''': predefined_args['''layer_norm_eps'''],
      '''max_position_embeddings''': predefined_args['''max_length'''],
      '''model_type''': '''bort''',
      '''num_attention_heads''': predefined_args['''num_heads'''],
      '''num_hidden_layers''': predefined_args['''num_layers'''],
      '''pad_token_id''': 1,  # 2 = BERT, 1 = RoBERTa
      '''type_vocab_size''': 1,  # 2 = BERT, 1 = RoBERTa
      '''vocab_size''': len(__lowerCAmelCase				),
  }

  lowerCAmelCase__										=      BertConfig.from_dict(__lowerCAmelCase				)
  lowerCAmelCase__										=      BertForMaskedLM(__lowerCAmelCase				)
  hf_bort_model.eval()

  # Parameter mapping table (Gluonnlp to Transformers)
  # * denotes layer index
  #
  # | Gluon Parameter                                                | Transformers Parameter
  # | -------------------------------------------------------------- | ----------------------
  # | `encoder.layer_norm.beta`                                      | `bert.embeddings.LayerNorm.bias`
  # | `encoder.layer_norm.gamma`                                     | `bert.embeddings.LayerNorm.weight`
  # | `encoder.position_weight`                                      | `bert.embeddings.position_embeddings.weight`
  # | `word_embed.0.weight`                                          | `bert.embeddings.word_embeddings.weight`
  # | `encoder.transformer_cells.*.attention_cell.proj_key.bias`     | `bert.encoder.layer.*.attention.self.key.bias`
  # | `encoder.transformer_cells.*.attention_cell.proj_key.weight`   | `bert.encoder.layer.*.attention.self.key.weight`
  # | `encoder.transformer_cells.*.attention_cell.proj_query.bias`   | `bert.encoder.layer.*.attention.self.query.bias`
  # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight`
  # | `encoder.transformer_cells.*.attention_cell.proj_value.bias`   | `bert.encoder.layer.*.attention.self.value.bias`
  # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight`
  # | `encoder.transformer_cells.*.ffn.ffn_2.bias`                   | `bert.encoder.layer.*.attention.output.dense.bias`
  # | `encoder.transformer_cells.*.ffn.ffn_2.weight`                 | `bert.encoder.layer.*.attention.output.dense.weight`
  # | `encoder.transformer_cells.*.layer_norm.beta`                  | `bert.encoder.layer.*.attention.output.LayerNorm.bias`
  # | `encoder.transformer_cells.*.layer_norm.gamma`                 | `bert.encoder.layer.*.attention.output.LayerNorm.weight`
  # | `encoder.transformer_cells.*.ffn.ffn_1.bias`                   | `bert.encoder.layer.*.intermediate.dense.bias`
  # | `encoder.transformer_cells.*.ffn.ffn_1.weight`                 | `bert.encoder.layer.*.intermediate.dense.weight`
  # | `encoder.transformer_cells.*.ffn.layer_norm.beta`              | `bert.encoder.layer.*.output.LayerNorm.bias`
  # | `encoder.transformer_cells.*.ffn.layer_norm.gamma`             | `bert.encoder.layer.*.output.LayerNorm.weight`
  # | `encoder.transformer_cells.*.proj.bias`                        | `bert.encoder.layer.*.output.dense.bias`
  # | `encoder.transformer_cells.*.proj.weight`                      | `bert.encoder.layer.*.output.dense.weight`

  # Helper function to convert MXNET Arrays to PyTorch
  def to_torch(__lowerCAmelCase				) -> nn.Parameter:
    return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy()				)				)

  # Check param shapes and map new HF param back
  def check_and_map_params(__lowerCAmelCase   , __lowerCAmelCase				):
    lowerCAmelCase__										=      hf_param.shape

    lowerCAmelCase__										=      to_torch(params[gluon_param]				)
    lowerCAmelCase__										=      gluon_param.shape

    assert (
        shape_hf == shape_gluon
    ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers"""

    return gluon_param

  lowerCAmelCase__										=      check_and_map_params(
      hf_bort_model.bert.embeddings.word_embeddings.weight   , '''word_embed.0.weight'''				)
  lowerCAmelCase__										=      check_and_map_params(
      hf_bort_model.bert.embeddings.position_embeddings.weight   , '''encoder.position_weight'''				)
  lowerCAmelCase__										=      check_and_map_params(
      hf_bort_model.bert.embeddings.LayerNorm.bias   , '''encoder.layer_norm.beta'''				)
  lowerCAmelCase__										=      check_and_map_params(
      hf_bort_model.bert.embeddings.LayerNorm.weight   , '''encoder.layer_norm.gamma'''				)

  # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them)
  lowerCAmelCase__										=      torch.zeros_like(
      hf_bort_model.bert.embeddings.token_type_embeddings.weight.data				)

  for i in range(hf_bort_config.num_hidden_layers				):
    lowerCAmelCase__										=      hf_bort_model.bert.encoder.layer[i]

    # self attention
    lowerCAmelCase__										=      layer.attention.self

    lowerCAmelCase__										=      check_and_map_params(
        self_attn.key.bias.data   , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias"""				)

    lowerCAmelCase__										=      check_and_map_params(
        self_attn.key.weight.data   , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight"""				)
    lowerCAmelCase__										=      check_and_map_params(
        self_attn.query.bias.data   , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias"""				)
    lowerCAmelCase__										=      check_and_map_params(
        self_attn.query.weight.data   , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight"""				)
    lowerCAmelCase__										=      check_and_map_params(
        self_attn.value.bias.data   , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias"""				)
    lowerCAmelCase__										=      check_and_map_params(
        self_attn.value.weight.data   , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight"""				)

    # self attention output
    lowerCAmelCase__										=      layer.attention.output

    lowerCAmelCase__										=      check_and_map_params(
        self_output.dense.bias   , F"""encoder.transformer_cells.{i}.proj.bias"""				)
    lowerCAmelCase__										=      check_and_map_params(
        self_output.dense.weight   , F"""encoder.transformer_cells.{i}.proj.weight"""				)
    lowerCAmelCase__										=      check_and_map_params(
        self_output.LayerNorm.bias   , F"""encoder.transformer_cells.{i}.layer_norm.beta"""				)
    lowerCAmelCase__										=      check_and_map_params(
        self_output.LayerNorm.weight   , F"""encoder.transformer_cells.{i}.layer_norm.gamma"""				)

    # intermediate
    lowerCAmelCase__										=      layer.intermediate

    lowerCAmelCase__										=      check_and_map_params(
        intermediate.dense.bias   , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias"""				)
    lowerCAmelCase__										=      check_and_map_params(
        intermediate.dense.weight   , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight"""				)

    # output
    lowerCAmelCase__										=      layer.output

    lowerCAmelCase__										=      check_and_map_params(
        bert_output.dense.bias   , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias"""				)
    lowerCAmelCase__										=      check_and_map_params(
        bert_output.dense.weight   , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight"""				)
    lowerCAmelCase__										=      check_and_map_params(
        bert_output.LayerNorm.bias   , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta"""				)
    lowerCAmelCase__										=      check_and_map_params(
        bert_output.LayerNorm.weight   , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma"""				)

  # Save space and energy 🎄
  hf_bort_model.half()

  # Compare output of both models
  lowerCAmelCase__										=      RobertaTokenizer.from_pretrained('''roberta-base'''				)

  lowerCAmelCase__										=      tokenizer.encode_plus(__lowerCAmelCase				)['''input_ids''']

  # Get gluon output
  lowerCAmelCase__										=      mx.nd.array([input_ids]				)
  lowerCAmelCase__										=      original_bort(inputs=__lowerCAmelCase   , token_types=[]				)

  # Get Transformer output (save and reload model again)
  hf_bort_model.save_pretrained(__lowerCAmelCase				)
  lowerCAmelCase__										=      BertModel.from_pretrained(__lowerCAmelCase				)
  hf_bort_model.eval()

  lowerCAmelCase__										=      tokenizer.encode_plus(__lowerCAmelCase   , return_tensors='''pt'''				)
  lowerCAmelCase__										=      hf_bort_model(**__lowerCAmelCase				)[0]

  lowerCAmelCase__										=      output_gluon[0].asnumpy()
  lowerCAmelCase__										=      output_hf[0].detach().numpy()

  lowerCAmelCase__										=      np.max(np.abs(hf_layer - gluon_layer				)				).item()
  lowerCAmelCase__										=      np.allclose(__lowerCAmelCase   , __lowerCAmelCase   , atol=1E-3				)

  if success:
    print('''✔️ Both model do output the same tensors'''				)
  else:
    print('''❌ Both model do **NOT** output the same tensors'''				)
    print('''Absolute difference is:'''   , __lowerCAmelCase				)


if __name__ == "__main__":
      __magic_name__  :  Any					=       argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          """--bort_checkpoint_path""", default=None, type=str, required=True, help="""Path the official Bort params file."""
      )
      parser.add_argument(
          """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
      )
      __magic_name__  :  int					=       parser.parse_args()
      convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)

