

'''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


lowerCAmelCase__											=	logging.get_logger(__name__)

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






@dataclass
class 			lowercase_	:




  """simple docstring"""




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






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Optional[Any]							=			'train'
  SCREAMING_SNAKE_CASE    :  List[Any]							=			'dev'






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  SquadDataTrainingArguments
  SCREAMING_SNAKE_CASE    :  List[SquadFeatures]
  SCREAMING_SNAKE_CASE    :  Split
  SCREAMING_SNAKE_CASE    :  bool






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

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

     __lowercase  ,	__lowercase							  = squad_convert_examples_to_features(
         examples=self.examples					,tokenizer=lowercase__					,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=lowercase__					,)

     __lowercase							  = time.time()
     torch.save(
         {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}					,lowercase__					,)
     # ^ 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			):
   return len(self.features			)






  def __getitem__(      self   :     Tuple					,lowercase__   :     str			):
   # Convert to Tensors and build dataset
   __lowercase							  = self.features[i]

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

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

   return inputs




'''simple docstring'''






import torch
from torch import nn






class 			lowercase_	(nn.Module      ):




  """simple docstring"""




  def __init__(      self   :     Optional[int]					,lowercase__   :     List[str]					,lowercase__   :     Any					,lowercase__   :     Union[str, Any]					,lowercase__   :     Optional[int]					,lowercase__   :     Optional[int]=1					,lowercase__   :     Optional[Any]=False			):
   super().__init__()

   __lowercase							  = n_token
   __lowercase							  = d_embed
   __lowercase							  = d_proj

   __lowercase							  = cutoffs + [n_token]
   __lowercase							  = [0] + self.cutoffs
   __lowercase							  = div_val

   __lowercase							  = self.cutoffs[0]
   __lowercase							  = len(self.cutoffs			) - 1
   __lowercase							  = self.shortlist_size + self.n_clusters

   if self.n_clusters > 0:
    __lowercase							  = nn.Parameter(torch.zeros(self.n_clusters					,self.d_embed			)			)
    __lowercase							  = nn.Parameter(torch.zeros(self.n_clusters			)			)

   __lowercase							  = nn.ModuleList()
   __lowercase							  = nn.ParameterList()

   if div_val == 1:
    for i in range(len(self.cutoffs			)			):
     if d_proj != d_embed:
      self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase__					,lowercase__			)			)			)
     else:
      self.out_projs.append(lowercase__			)

    self.out_layers.append(nn.Linear(lowercase__					,lowercase__			)			)
   else:
    for i in range(len(self.cutoffs			)			):
     __lowercase  ,	__lowercase							  = self.cutoff_ends[i], self.cutoff_ends[i + 1]
     __lowercase							  = d_embed // (div_val**i)

     self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase__					,lowercase__			)			)			)

     self.out_layers.append(nn.Linear(lowercase__					,r_idx - l_idx			)			)

   __lowercase							  = keep_order






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]					,lowercase__   :     List[Any]					,lowercase__   :     Dict					,lowercase__   :     List[Any]					,lowercase__   :     Any			):
   if proj is None:
    __lowercase							  = nn.functional.linear(lowercase__					,lowercase__					,bias=lowercase__			)
   else:
    # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
    __lowercase							  = nn.functional.linear(lowercase__					,proj.t().contiguous()			)
    __lowercase							  = nn.functional.linear(lowercase__					,lowercase__					,bias=lowercase__			)
    # else:
    #     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
    #     if bias is not None:
    #         logit = logit + bias

   return logit






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]					,lowercase__   :     Optional[Any]					,lowercase__   :     Any=None					,lowercase__   :     List[str]=False			):

   if labels is not None:
    # Shift so that tokens < n predict n
    __lowercase							  = hidden[..., :-1, :].contiguous()
    __lowercase							  = labels[..., 1:].contiguous()
    __lowercase							  = hidden.view(-1					,hidden.size(-1			)			)
    __lowercase							  = labels.view(-1			)
    if hidden.size(0			) != labels.size(0			):
     raise RuntimeError('''Input and labels should have the same size in the batch dimension.'''			)
   else:
    __lowercase							  = hidden.view(-1					,hidden.size(-1			)			)

   if self.n_clusters == 0:
    __lowercase							  = self._compute_logit(lowercase__					,self.out_layers[0].weight					,self.out_layers[0].bias					,self.out_projs[0]			)
    if labels is not None:
     __lowercase							  = labels != -1_0_0
     __lowercase							  = torch.zeros_like(lowercase__					,dtype=hidden.dtype					,device=hidden.device			)
     __lowercase							  = (
         -nn.functional.log_softmax(lowercase__					,dim=-1			)[mask].gather(1					,labels[mask].unsqueeze(1			)			).squeeze(1			)
     )
    else:
     __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=-1			)
   else:
    # construct weights and biases
    __lowercase  ,	__lowercase							  = [], []
    for i in range(len(self.cutoffs			)			):
     if self.div_val == 1:
      __lowercase  ,	__lowercase							  = self.cutoff_ends[i], self.cutoff_ends[i + 1]
      __lowercase							  = self.out_layers[0].weight[l_idx:r_idx]
      __lowercase							  = self.out_layers[0].bias[l_idx:r_idx]
     else:
      __lowercase							  = self.out_layers[i].weight
      __lowercase							  = self.out_layers[i].bias

     if i == 0:
      __lowercase							  = torch.cat([weight_i, self.cluster_weight]					,dim=0			)
      __lowercase							  = torch.cat([bias_i, self.cluster_bias]					,dim=0			)

     weights.append(lowercase__			)
     biases.append(lowercase__			)

    __lowercase  ,	__lowercase  ,	__lowercase							  = weights[0], biases[0], self.out_projs[0]

    __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)
    __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)

    if labels is None:
     __lowercase							  = hidden.new_empty((head_logit.size(0			), self.n_token)			)
    else:
     __lowercase							  = torch.zeros_like(lowercase__					,dtype=hidden.dtype					,device=hidden.device			)

    __lowercase							  = 0
    __lowercase							  = [0] + self.cutoffs
    for i in range(len(lowercase__			) - 1			):
     __lowercase  ,	__lowercase							  = cutoff_values[i], cutoff_values[i + 1]

     if labels is not None:
      __lowercase							  = (labels >= l_idx) & (labels < r_idx)
      __lowercase							  = mask_i.nonzero().squeeze()

      if indices_i.numel() == 0:
       continue

      __lowercase							  = labels.index_select(0					,lowercase__			) - l_idx
      __lowercase							  = head_logprob.index_select(0					,lowercase__			)
      __lowercase							  = hidden.index_select(0					,lowercase__			)
     else:
      __lowercase							  = hidden

     if i == 0:
      if labels is not None:
       __lowercase							  = head_logprob_i.gather(1					,target_i[:, None]			).squeeze(1			)
      else:
       __lowercase							  = head_logprob[:, : self.cutoffs[0]]
     else:
      __lowercase  ,	__lowercase  ,	__lowercase							  = weights[i], biases[i], self.out_projs[i]

      __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)
      __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)
      __lowercase							  = self.cutoffs[0] + i - 1  # No probability for the head cluster
      if labels is not None:
       __lowercase							  = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
           1					,target_i[:, None]			).squeeze(1			)
      else:
       __lowercase							  = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
       __lowercase							  = logprob_i

     if labels is not None:
      if (hasattr(self					,'''keep_order'''			) and self.keep_order) or keep_order:
       out.index_copy_(0					,lowercase__					,-logprob_i			)
      else:
       out[offset : offset + logprob_i.size(0			)].copy_(-logprob_i			)
      offset += logprob_i.size(0			)

   return out






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any					,lowercase__   :     Union[str, Any]			):
   if self.n_clusters == 0:
    __lowercase							  = self._compute_logit(lowercase__					,self.out_layers[0].weight					,self.out_layers[0].bias					,self.out_projs[0]			)
    return nn.functional.log_softmax(lowercase__					,dim=-1			)
   else:
    # construct weights and biases
    __lowercase  ,	__lowercase							  = [], []
    for i in range(len(self.cutoffs			)			):
     if self.div_val == 1:
      __lowercase  ,	__lowercase							  = self.cutoff_ends[i], self.cutoff_ends[i + 1]
      __lowercase							  = self.out_layers[0].weight[l_idx:r_idx]
      __lowercase							  = self.out_layers[0].bias[l_idx:r_idx]
     else:
      __lowercase							  = self.out_layers[i].weight
      __lowercase							  = self.out_layers[i].bias

     if i == 0:
      __lowercase							  = torch.cat([weight_i, self.cluster_weight]					,dim=0			)
      __lowercase							  = torch.cat([bias_i, self.cluster_bias]					,dim=0			)

     weights.append(lowercase__			)
     biases.append(lowercase__			)

    __lowercase  ,	__lowercase  ,	__lowercase							  = weights[0], biases[0], self.out_projs[0]
    __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)

    __lowercase							  = hidden.new_empty((head_logit.size(0			), self.n_token)			)
    __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)

    __lowercase							  = [0] + self.cutoffs
    for i in range(len(lowercase__			) - 1			):
     __lowercase  ,	__lowercase							  = cutoff_values[i], cutoff_values[i + 1]

     if i == 0:
      __lowercase							  = head_logprob[:, : self.cutoffs[0]]
     else:
      __lowercase  ,	__lowercase  ,	__lowercase							  = weights[i], biases[i], self.out_projs[i]

      __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)
      __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)

      __lowercase							  = head_logprob[:, -i] + tail_logprob_i
      __lowercase							  = logprob_i

    return out

