





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


_snake_case    :       str		       =    logging.get_logger(__name__)

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



@dataclass
class 							_UpperCAmelCase       :

  """simple docstring"""


  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """Model type selected in the list: """ + """, """.join(_UpperCamelCase       )}       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}       )
  a_              =					field(
      default=1_28						,       metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }						,       )
  a_              =					field(
      default=1_28						,       metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}						,       )
  a_              =					field(
      default=64						,       metadata={
          """help""": (
              """The maximum number of tokens for the question. Questions longer than this will """
              """be truncated to this length."""
          )
      }						,       )
  a_              =					field(
      default=30						,       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_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}       )
  a_              =					field(
      default=0.0						,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  a_              =					field(
      default=20						,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  a_              =					field(
      default=0						,       metadata={
          """help""": (
              """language id of input for language-specific xlm models (see"""
              """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
          )
      }						,       )
  a_              =					field(default=1						,       metadata={"""help""": """multiple threads for converting example to features"""}       )





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					"""train"""
  a_              =					"""dev"""





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					42






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

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

           __lowerCAmelCase      ,      __lowerCAmelCase				      =      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_   ,    )

           __lowerCAmelCase				      =      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					:						Tuple	)				->		List[str]:
     return len(self.features	)






  def __getitem__(							self					:						Dict   ,    lowerCAmelCase_					:						Optional[int]	)				->		Dict[str, torch.Tensor]:
     # Convert to Tensors and build dataset
     __lowerCAmelCase				      =      self.features[i]

     __lowerCAmelCase				      =      torch.tensor(feature.input_ids   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.attention_mask   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.token_type_ids   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.cls_index   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.p_mask   ,    dtype=torch.float	)
     __lowerCAmelCase				      =      torch.tensor(feature.is_impossible   ,    dtype=torch.float	)

     __lowerCAmelCase				      =      {
         '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:
        __lowerCAmelCase				      =      torch.tensor(feature.start_position   ,    dtype=torch.long	)
        __lowerCAmelCase				      =      torch.tensor(feature.end_position   ,    dtype=torch.long	)
        inputs.update({'start_positions': start_positions, 'end_positions': end_positions}	)

     return inputs





import os

import torch

from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version


if is_torch_version(">=", FSDP_PYTORCH_VERSION):
		import torch.distributed.checkpoint as dist_cp
		from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
		from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
		from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
		from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType


SCREAMING_SNAKE_CASE__     					=			get_logger(__name__)


def     lowercase	(    a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		os.makedirs(a     , exist_ok=a )
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						model.state_dict()
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:Optional[int]				     =						F"{MODEL_NAME}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}.bin"
						SCREAMING_SNAKE_CASE_				:str				     =						os.path.join(a     , a )
						if accelerator.process_index == 0:
								logger.info(F"Saving model to {output_model_file}" )
								torch.save(a     , a )
								logger.info(F"Model saved to {output_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:Tuple				     =						(
						    F"{MODEL_NAME}_rank{accelerator.process_index}.bin"
						    if model_index == 0
						    else F"{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"
						)
						SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						os.path.join(a     , a )
						logger.info(F"Saving model to {output_model_file}" )
						torch.save(a     , a )
						logger.info(F"Model saved to {output_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:Dict				     =						os.path.join(a     , F"{MODEL_NAME}_{model_index}" )
						os.makedirs(a     , exist_ok=a )
						logger.info(F"Saving model to {ckpt_dir}" )
						SCREAMING_SNAKE_CASE_				:int				     =						{"model": state_dict}

						dist_cp.save_state_dict(
						    state_dict=a     , storage_writer=dist_cp.FileSystemWriter(a )     , planner=DefaultSavePlanner()     , )
						logger.info(F"Model saved to {ckpt_dir}" )


def     lowercase	(    a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		accelerator.wait_for_everyone()
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						if type(a ) != FSDP and accelerator.process_index != 0:
								if not fsdp_plugin.sync_module_states:
										raise ValueError(
										    "Set the `sync_module_states` flag to `True` so that model states are synced across processes when "
										    "initializing FSDP object" )
								return
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						F"{MODEL_NAME}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}.bin"
						SCREAMING_SNAKE_CASE_				:int				     =						os.path.join(a     , a )
						logger.info(F"Loading model from {input_model_file}" )
						SCREAMING_SNAKE_CASE_				:Dict				     =						torch.load(a )
						logger.info(F"Model loaded from {input_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:int				     =						(
						    F"{MODEL_NAME}_rank{accelerator.process_index}.bin"
						    if model_index == 0
						    else F"{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"
						)
						SCREAMING_SNAKE_CASE_				:int				     =						os.path.join(a     , a )
						logger.info(F"Loading model from {input_model_file}" )
						SCREAMING_SNAKE_CASE_				:Dict				     =						torch.load(a )
						logger.info(F"Model loaded from {input_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:List[str]				     =						(
						    os.path.join(a     , F"{MODEL_NAME}_{model_index}" )
						    if F"{MODEL_NAME}" not in input_dir
						    else input_dir
						)
						logger.info(F"Loading model from {ckpt_dir}" )
						SCREAMING_SNAKE_CASE_				:Any				     =						{"model": model.state_dict()}
						dist_cp.load_state_dict(
						    state_dict=a     , storage_reader=dist_cp.FileSystemReader(a )     , planner=DefaultLoadPlanner()     , )
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						state_dict["model"]
						logger.info(F"Model loaded from {ckpt_dir}" )
				model.load_state_dict(a )


def     lowercase	(    a     , a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		os.makedirs(a     , exist_ok=a )
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				SCREAMING_SNAKE_CASE_				:str				     =						FSDP.optim_state_dict(a     , a )
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						if accelerator.process_index == 0:
								SCREAMING_SNAKE_CASE_				:List[str]				     =						(
								    F"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else F"{OPTIMIZER_NAME}_{optimizer_index}.bin"
								)
								SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						os.path.join(a     , a )
								logger.info(F"Saving Optimizer state to {output_optimizer_file}" )
								torch.save(a     , a )
								logger.info(F"Optimizer state saved in {output_optimizer_file}" )
				else:
						SCREAMING_SNAKE_CASE_				:Any				     =						os.path.join(a     , F"{OPTIMIZER_NAME}_{optimizer_index}" )
						os.makedirs(a     , exist_ok=a )
						logger.info(F"Saving Optimizer state to {ckpt_dir}" )
						dist_cp.save_state_dict(
						    state_dict={"optimizer": optim_state}     , storage_writer=dist_cp.FileSystemWriter(a )     , planner=DefaultSavePlanner()     , )
						logger.info(F"Optimizer state saved in {ckpt_dir}" )


def     lowercase	(    a     , a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		accelerator.wait_for_everyone()
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:List[str]				     =						None
						# below check should work but currently it isn't working (mostly opytorch issue),
						# in the meantime disabling it at the cost of excess memory usage
						# if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						(
						    F"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else F"{OPTIMIZER_NAME}_{optimizer_index}.bin"
						)
						SCREAMING_SNAKE_CASE_				:Dict				     =						os.path.join(a     , a )
						logger.info(F"Loading Optimizer state from {input_optimizer_file}" )
						SCREAMING_SNAKE_CASE_				:str				     =						torch.load(a )
						logger.info(F"Optimizer state loaded from {input_optimizer_file}" )
				else:
						SCREAMING_SNAKE_CASE_				:Any				     =						(
						    os.path.join(a     , F"{OPTIMIZER_NAME}_{optimizer_index}" )
						    if F"{OPTIMIZER_NAME}" not in input_dir
						    else input_dir
						)
						logger.info(F"Loading Optimizer from {ckpt_dir}" )
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						load_sharded_optimizer_state_dict(
						    model_state_dict=model.state_dict()     , optimizer_key="optimizer"     , storage_reader=dist_cp.FileSystemReader(a )     , )
						SCREAMING_SNAKE_CASE_				:List[str]				     =						optim_state["optimizer"]
						logger.info(F"Optimizer loaded from {ckpt_dir}" )
				SCREAMING_SNAKE_CASE_				:int				     =						FSDP.optim_state_dict_to_load(a     , a     , a )
				optimizer.load_state_dict(a )






