


import argparse
import collections

import numpy as np
import torch
from flax import traverse_util
from tax import checkpoints

from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()

def 			_a  (				SCREAMING_SNAKE_CASE	:				Optional[int]    , SCREAMING_SNAKE_CASE	:				str    , SCREAMING_SNAKE_CASE	:				int     ):







 """simple docstring"""



 return params[F"{prefix}/{prefix}/relpos_bias/rel_embedding"][:, i, :]

def 			_a  (				SCREAMING_SNAKE_CASE	:				int    , SCREAMING_SNAKE_CASE	:				str    , SCREAMING_SNAKE_CASE	:				Tuple    , SCREAMING_SNAKE_CASE	:				Optional[int]="attention"     ):







 """simple docstring"""



 UpperCamelCase__					:    Union[str, Any]          =   np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/key/kernel"][:, i, :, :]     )
 UpperCamelCase__					:    Optional[Any]          =   k_tmp.reshape(k_tmp.shape[0]    , k_tmp.shape[1] * k_tmp.shape[2]     )
 UpperCamelCase__					:    int          =   np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/out/kernel"][:, i, :, :]     )
 UpperCamelCase__					:    List[str]          =   o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1]    , o_tmp.shape[2]     )
 UpperCamelCase__					:    str          =   np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/query/kernel"][:, i, :, :]     )
 UpperCamelCase__					:    Optional[Any]          =   q_tmp.reshape(q_tmp.shape[0]    , q_tmp.shape[1] * q_tmp.shape[2]     )
 UpperCamelCase__					:    Optional[int]          =   np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/value/kernel"][:, i, :, :]     )
 UpperCamelCase__					:    Tuple          =   v_tmp.reshape(v_tmp.shape[0]    , v_tmp.shape[1] * v_tmp.shape[2]     )
 return k, o, q, v

def 			_a  (				SCREAMING_SNAKE_CASE	:				Tuple    , SCREAMING_SNAKE_CASE	:				Tuple    , SCREAMING_SNAKE_CASE	:				Dict    , SCREAMING_SNAKE_CASE	:				str=False     ):







 """simple docstring"""



 if split_mlp_wi:
  UpperCamelCase__					:    Optional[Any]          =   params[F"{prefix}/{prefix}/mlp/wi_0/kernel"][:, i, :]
  UpperCamelCase__					:    Dict          =   params[F"{prefix}/{prefix}/mlp/wi_1/kernel"][:, i, :]
  UpperCamelCase__					:    Union[str, Any]          =   (wi_a, wi_a)
 else:
  UpperCamelCase__					:    List[str]          =   params[F"{prefix}/{prefix}/mlp/wi/kernel"][:, i, :]

 UpperCamelCase__					:    List[str]          =   params[F"{prefix}/{prefix}/mlp/wo/kernel"][:, i, :]
 return wi, wo

def 			_a  (				SCREAMING_SNAKE_CASE	:				List[Any]    , SCREAMING_SNAKE_CASE	:				Union[str, Any]    , SCREAMING_SNAKE_CASE	:				Optional[Any]    , SCREAMING_SNAKE_CASE	:				Tuple     ):







 """simple docstring"""



 return params[F"{prefix}/{prefix}/{layer_name}/scale"][:, i]

def 			_a  (				SCREAMING_SNAKE_CASE	:				dict    , *, SCREAMING_SNAKE_CASE	:				int    , SCREAMING_SNAKE_CASE	:				bool    , SCREAMING_SNAKE_CASE	:				bool = False     ):







 """simple docstring"""



 UpperCamelCase__					:    Union[str, Any]          =   traverse_util.flatten_dict(variables['''target''']     )
 UpperCamelCase__					:    Dict          =   {'''/'''.join(SCREAMING_SNAKE_CASE     ): v for k, v in old.items()}

 # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
 UpperCamelCase__					:    List[str]          =   '''encoder/encoder/mlp/wi_0/kernel''' in old
 print('''Split MLP:'''    , SCREAMING_SNAKE_CASE     )

 UpperCamelCase__					:    Dict          =   collections.OrderedDict()

 # Shared embeddings.
 UpperCamelCase__					:    str          =   old['''token_embedder/embedding''']

 # Encoder.
 for i in range(SCREAMING_SNAKE_CASE     ):
  # Block i, layer 0 (Self Attention).
  UpperCamelCase__					:    Dict          =   tax_layer_norm_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''encoder'''    , '''pre_attention_layer_norm'''     )
  UpperCamelCase__       ,				UpperCamelCase__       ,				UpperCamelCase__       ,				UpperCamelCase__					:    Union[str, Any]          =   tax_attention_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''encoder'''    , '''attention'''     )
  UpperCamelCase__					:    Optional[int]          =   layer_norm
  UpperCamelCase__					:    Optional[int]          =   k.T
  UpperCamelCase__					:    Union[str, Any]          =   o.T
  UpperCamelCase__					:    Optional[Any]          =   q.T
  UpperCamelCase__					:    int          =   v.T

  # Block i, layer 1 (MLP).
  UpperCamelCase__					:    List[Any]          =   tax_layer_norm_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''encoder'''    , '''pre_mlp_layer_norm'''     )
  UpperCamelCase__       ,				UpperCamelCase__					:    Optional[Any]          =   tax_mlp_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''encoder'''    , SCREAMING_SNAKE_CASE     )
  UpperCamelCase__					:    Dict          =   layer_norm
  if split_mlp_wi:
   UpperCamelCase__					:    Tuple          =   wi[0].T
   UpperCamelCase__					:    Any          =   wi[1].T
  else:
   UpperCamelCase__					:    Dict          =   wi.T
  UpperCamelCase__					:    List[str]          =   wo.T
  if scalable_attention:
   # convert the rel_embedding of each layer
   UpperCamelCase__					:    Union[str, Any]          =   tax_relpos_bias_lookup(
       SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''encoder'''     ).T

 UpperCamelCase__					:    str          =   old['''encoder/encoder_norm/scale''']

 if not scalable_attention:
  UpperCamelCase__					:    Any          =   tax_relpos_bias_lookup(
      SCREAMING_SNAKE_CASE    , 0    , '''encoder'''     ).T
  UpperCamelCase__					:    Optional[Any]          =   tax_relpos_bias_lookup(
      SCREAMING_SNAKE_CASE    , 0    , '''decoder'''     ).T

 if not is_encoder_only:
  # Decoder.
  for i in range(SCREAMING_SNAKE_CASE     ):
   # Block i, layer 0 (Self Attention).
   UpperCamelCase__					:    Union[str, Any]          =   tax_layer_norm_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''decoder'''    , '''pre_self_attention_layer_norm'''     )
   UpperCamelCase__       ,				UpperCamelCase__       ,				UpperCamelCase__       ,				UpperCamelCase__					:    Optional[Any]          =   tax_attention_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''decoder'''    , '''self_attention'''     )
   UpperCamelCase__					:    Tuple          =   layer_norm
   UpperCamelCase__					:    Union[str, Any]          =   k.T
   UpperCamelCase__					:    int          =   o.T
   UpperCamelCase__					:    str          =   q.T
   UpperCamelCase__					:    Any          =   v.T

   # Block i, layer 1 (Cross Attention).
   UpperCamelCase__					:    Any          =   tax_layer_norm_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''decoder'''    , '''pre_cross_attention_layer_norm'''     )
   UpperCamelCase__       ,				UpperCamelCase__       ,				UpperCamelCase__       ,				UpperCamelCase__					:    Union[str, Any]          =   tax_attention_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''decoder'''    , '''encoder_decoder_attention'''     )
   UpperCamelCase__					:    int          =   layer_norm
   UpperCamelCase__					:    Optional[int]          =   k.T
   UpperCamelCase__					:    Tuple          =   o.T
   UpperCamelCase__					:    List[str]          =   q.T
   UpperCamelCase__					:    List[Any]          =   v.T

   # Block i, layer 2 (MLP).
   UpperCamelCase__					:    List[Any]          =   tax_layer_norm_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''decoder'''    , '''pre_mlp_layer_norm'''     )
   UpperCamelCase__       ,				UpperCamelCase__					:    Any          =   tax_mlp_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''decoder'''    , SCREAMING_SNAKE_CASE     )
   UpperCamelCase__					:    Union[str, Any]          =   layer_norm
   if split_mlp_wi:
    UpperCamelCase__					:    Dict          =   wi[0].T
    UpperCamelCase__					:    List[Any]          =   wi[1].T
   else:
    UpperCamelCase__					:    str          =   wi.T
   UpperCamelCase__					:    List[Any]          =   wo.T

   if scalable_attention:
    # convert the rel_embedding of each layer
    UpperCamelCase__					:    List[str]          =   tax_relpos_bias_lookup(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , '''decoder'''     ).T

  UpperCamelCase__					:    List[str]          =   old['''decoder/decoder_norm/scale''']

  # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
  if "decoder/logits_dense/kernel" in old:
   UpperCamelCase__					:    Optional[Any]          =   old['''decoder/logits_dense/kernel'''].T

 return new

def 			_a  (				SCREAMING_SNAKE_CASE	:				Dict    , SCREAMING_SNAKE_CASE	:				bool     ):







 """simple docstring"""



 UpperCamelCase__					:    Dict          =   collections.OrderedDict([(k, torch.from_numpy(v.copy()     )) for (k, v) in converted_params.items()]     )

 # Add what is missing.
 if "encoder.embed_tokens.weight" not in state_dict:
  UpperCamelCase__					:    List[str]          =   state_dict['''shared.weight''']

 if not is_encoder_only:
  if "decoder.embed_tokens.weight" not in state_dict:
   UpperCamelCase__					:    str          =   state_dict['''shared.weight''']

  if "lm_head.weight" not in state_dict:  # For old 1.0 models.
   print('''Using shared word embeddings as lm_head.'''     )
   UpperCamelCase__					:    Union[str, Any]          =   state_dict['''shared.weight''']

 return state_dict

def 			_a  (				SCREAMING_SNAKE_CASE	:				Union[str, Any]    , SCREAMING_SNAKE_CASE	:				Union[str, Any]    , SCREAMING_SNAKE_CASE	:				Any    , SCREAMING_SNAKE_CASE	:				Dict    , SCREAMING_SNAKE_CASE	:				Optional[int]     ):







 """simple docstring"""



 UpperCamelCase__					:    List[Any]          =   checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE     )
 UpperCamelCase__					:    Optional[Any]          =   convert_tax_to_pytorch(
     SCREAMING_SNAKE_CASE    , num_layers=config.num_layers    , is_encoder_only=SCREAMING_SNAKE_CASE    , scalable_attention=SCREAMING_SNAKE_CASE     )
 UpperCamelCase__					:    str          =   make_state_dict(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )
 model.load_state_dict(SCREAMING_SNAKE_CASE    , strict=SCREAMING_SNAKE_CASE     )

def 			_a  (				SCREAMING_SNAKE_CASE	:				Tuple    , SCREAMING_SNAKE_CASE	:				Tuple    , SCREAMING_SNAKE_CASE	:				str    , SCREAMING_SNAKE_CASE	:				bool = False    , SCREAMING_SNAKE_CASE	:				bool = False    , ):







 """simple docstring"""



 UpperCamelCase__					:    Optional[int]          =   MTaConfig.from_json_file(SCREAMING_SNAKE_CASE     )
 print(F"Building PyTorch model from configuration: {config}"     )
 # Non-v1.1 checkpoints could also use T5Model, but this works for all.
 # The v1.0 checkpoints will simply have an LM head that is the word embeddings.
 if is_encoder_only:
  UpperCamelCase__					:    Dict          =   UMTaEncoderModel(SCREAMING_SNAKE_CASE     )
 else:
  UpperCamelCase__					:    Union[str, Any]          =   UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE     )

 # Load weights from tf checkpoint
 load_tax_weights_in_ta(SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE    , SCREAMING_SNAKE_CASE     )

 # Save pytorch-model
 print(F"Save PyTorch model to {pytorch_dump_path}"     )
 model.save_pretrained(SCREAMING_SNAKE_CASE     )

 # Verify that we can load the checkpoint.
 model.from_pretrained(SCREAMING_SNAKE_CASE     )
 print('''Done'''     )


if __name__ == "__main__":
       __UpperCamelCase       :       str						       =				argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.")
       # Required parameters
       parser.add_argument(
           "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint."
       )
       parser.add_argument(
           "--config_file",
           default=None,
           type=str,
           required=True,
           help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.",
       )
       parser.add_argument(
           "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
       )
       parser.add_argument(
           "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False
       )
       parser.add_argument(
           "--scalable_attention",
           action="store_true",
           help="Whether the model uses scaled attention (umt5 model)",
           default=False,
       )
       __UpperCamelCase       :       int						       =				parser.parse_args()
       convert_tax_checkpoint_to_pytorch(
           args.tax_checkpoint_path,
           args.config_file,
           args.pytorch_dump_path,
           args.is_encoder_only,
           args.scalable_attention,
       )






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       :       List[str]						       =				logging.get_logger(__name__)

__UpperCamelCase       :       Union[str, Any]						       =				list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__UpperCamelCase       :       Dict						       =				tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class       __magic_name__	:
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "Model type selected in the list: " + ", ".join(__lowerCAmelCase)})
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."})
     A:		int			=      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."
             )
         }					,				)
     A:		int			=      field(
         default=1_2_8					,				metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}					,				)
     A:		int			=      field(
         default=6_4					,				metadata={
             "help": (
                 "The maximum number of tokens for the question. Questions longer than this will "
                 "be truncated to this length."
             )
         }					,				)
     A:		int			=      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."
             )
         }					,				)
     A:		bool			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "Overwrite the cached training and evaluation sets"})
     A:		bool			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."})
     A:		float			=      field(
         default=0.0					,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
     A:		int			=      field(
         default=2_0					,				metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
     A:		int			=      field(
         default=0					,				metadata={
             "help": (
                 "language id of input for language-specific xlm models (see"
                 " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
             )
         }					,				)
     A:		int			=      field(default=1					,				metadata={"help": "multiple threads for converting example to features"})



class       __magic_name__	(     __lowerCAmelCase):
     A:		Union[str, Any]			=      "train"
     A:		List[str]			=      "dev"



class       __magic_name__	(     __lowerCAmelCase):
     A:		SquadDataTrainingArguments
     A:		List[SquadFeatures]
     A:		Split
     A:		bool


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





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   args
      UpperCamelCase__					:    Union[str, Any]          =   is_language_sensitive
      UpperCamelCase__					:    List[Any]          =   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
      if isinstance(lowerCamelCase__							,	lowerCamelCase__			):
       try:
        UpperCamelCase__					:    Union[str, Any]          =   Split[mode]
       except KeyError:
        raise KeyError('''mode is not a valid split name'''			)
      UpperCamelCase__					:    List[str]          =   mode
      # Load data features from cache or dataset file
      UpperCamelCase__					:    List[str]          =   '''v2''' if args.version_2_with_negative else '''v1'''
      UpperCamelCase__					:    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__					:    Tuple          =   cached_features_file + '''.lock'''
      with FileLock(lowerCamelCase__			):
       if os.path.exists(lowerCamelCase__			) and not args.overwrite_cache:
        UpperCamelCase__					:    int          =   time.time()
        UpperCamelCase__					:    List[str]          =   torch.load(lowerCamelCase__			)

        # Legacy cache files have only features, while new cache files
        # will have dataset and examples also.
        UpperCamelCase__					:    Any          =   self.old_features['''features''']
        UpperCamelCase__					:    Union[str, Any]          =   self.old_features.get('''dataset'''							,	lowerCamelCase__			)
        UpperCamelCase__					:    List[str]          =   self.old_features.get('''examples'''							,	lowerCamelCase__			)
        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__					:    List[str]          =   self.processor.get_dev_examples(args.data_dir			)
        else:
         UpperCamelCase__					:    Any          =   self.processor.get_train_examples(args.data_dir			)

        UpperCamelCase__       ,				UpperCamelCase__					:    Union[str, Any]          =   squad_convert_examples_to_features(
            examples=self.examples							,	tokenizer=lowerCamelCase__							,	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=lowerCamelCase__							,	)

        UpperCamelCase__					:    Tuple          =   time.time()
        torch.save(
            {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}							,	lowerCamelCase__							,	)
        # ^ 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							:     Any			)  ->      List[str]:





      '''simple docstring'''






      return len(self.features			)


     def __getitem__(      self							:     Dict							,	lowerCamelCase__							:     Any			)  ->      Dict[str, torch.Tensor]:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   self.features[i]

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

      UpperCamelCase__					:    Dict          =   {
          '''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__					:    Optional[Any]          =   torch.tensor(feature.start_position							,	dtype=torch.long			)
       UpperCamelCase__					:    Optional[int]          =   torch.tensor(feature.end_position							,	dtype=torch.long			)
       inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}			)

      return inputs


