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


_a     :     str= logging.get_logger(__name__)

_a     :     Optional[Any]= list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_a     :     Optional[int]= tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

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







class 		UpperCamelCase			(    lowerCamelCase__						):
				UpperCAmelCase				:      Optional[Any]    =		'train'
				UpperCAmelCase				:      List[Any]    =		'dev'







class 		UpperCamelCase			(    lowerCamelCase__						):
				UpperCAmelCase				:      SquadDataTrainingArguments
				UpperCAmelCase				:      List[SquadFeatures]
				UpperCAmelCase				:      Split
				UpperCAmelCase				:      bool



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

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

							__snake_case		,				__snake_case			:							Optional[int]      		= 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__	,  )

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






				def __getitem__(self				:      Tuple	,  _A				:      str)    ->	Optional[Any]:
					# Convert to Tensors and build dataset
					__snake_case			:							Optional[Any]      		= self.features[i]

					__snake_case			:							Union[str, Any]      		= torch.tensor(feature.input_ids	,  dtype=torch.long)
					__snake_case			:							Dict      		= torch.tensor(feature.attention_mask	,  dtype=torch.long)
					__snake_case			:							Tuple      		= torch.tensor(feature.token_type_ids	,  dtype=torch.long)
					__snake_case			:							List[str]      		= torch.tensor(feature.cls_index	,  dtype=torch.long)
					__snake_case			:							Union[str, Any]      		= torch.tensor(feature.p_mask	,  dtype=torch.float)
					__snake_case			:							Any      		= torch.tensor(feature.is_impossible	,  dtype=torch.float)

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

					return inputs








'''simple docstring'''






from __future__ import annotations

from decimal import Decimal

from numpy import array


def 		_A     (    A__      ):






 """simple docstring"""



 __lowercase							  = Decimal

 # Check if the provided matrix has 2 rows and 2 columns
 # since this implementation only works for 2x2 matrices
 if len(A__      ) == 2 and len(matrix[0]      ) == 2 and len(matrix[1]      ) == 2:
  # Calculate the determinant of the matrix
  __lowercase							  = float(
      d(matrix[0][0]      ) * d(matrix[1][1]      ) - d(matrix[1][0]      ) * d(matrix[0][1]      )      )
  if determinant == 0:
   raise ValueError('''This matrix has no inverse.'''      )

  # Creates a copy of the matrix with swapped positions of the elements
  __lowercase							  = [[0.0, 0.0], [0.0, 0.0]]
  __lowercase  ,	__lowercase							  = matrix[1][1], matrix[0][0]
  __lowercase  ,	__lowercase							  = -matrix[1][0], -matrix[0][1]

  # Calculate the inverse of the matrix
  return [
      [(float(d(A__      )      ) / determinant) or 0.0 for n in row] for row in swapped_matrix
  ]
 elif (
     len(A__      ) == 3
     and len(matrix[0]      ) == 3
     and len(matrix[1]      ) == 3
     and len(matrix[2]      ) == 3
 ):
  # Calculate the determinant of the matrix using Sarrus rule
  __lowercase							  = float(
      (
          (d(matrix[0][0]      ) * d(matrix[1][1]      ) * d(matrix[2][2]      ))
          + (d(matrix[0][1]      ) * d(matrix[1][2]      ) * d(matrix[2][0]      ))
          + (d(matrix[0][2]      ) * d(matrix[1][0]      ) * d(matrix[2][1]      ))
      )
      - (
          (d(matrix[0][2]      ) * d(matrix[1][1]      ) * d(matrix[2][0]      ))
          + (d(matrix[0][1]      ) * d(matrix[1][0]      ) * d(matrix[2][2]      ))
          + (d(matrix[0][0]      ) * d(matrix[1][2]      ) * d(matrix[2][1]      ))
      )      )
  if determinant == 0:
   raise ValueError('''This matrix has no inverse.'''      )

  # Creating cofactor matrix
  __lowercase							  = [
      [d(0.0      ), d(0.0      ), d(0.0      )],
      [d(0.0      ), d(0.0      ), d(0.0      )],
      [d(0.0      ), d(0.0      ), d(0.0      )],
  ]
  __lowercase							  = (d(matrix[1][1]      ) * d(matrix[2][2]      )) - (
      d(matrix[1][2]      ) * d(matrix[2][1]      )
  )
  __lowercase							  = -(
      (d(matrix[1][0]      ) * d(matrix[2][2]      )) - (d(matrix[1][2]      ) * d(matrix[2][0]      ))
  )
  __lowercase							  = (d(matrix[1][0]      ) * d(matrix[2][1]      )) - (
      d(matrix[1][1]      ) * d(matrix[2][0]      )
  )
  __lowercase							  = -(
      (d(matrix[0][1]      ) * d(matrix[2][2]      )) - (d(matrix[0][2]      ) * d(matrix[2][1]      ))
  )
  __lowercase							  = (d(matrix[0][0]      ) * d(matrix[2][2]      )) - (
      d(matrix[0][2]      ) * d(matrix[2][0]      )
  )
  __lowercase							  = -(
      (d(matrix[0][0]      ) * d(matrix[2][1]      )) - (d(matrix[0][1]      ) * d(matrix[2][0]      ))
  )
  __lowercase							  = (d(matrix[0][1]      ) * d(matrix[1][2]      )) - (
      d(matrix[0][2]      ) * d(matrix[1][1]      )
  )
  __lowercase							  = -(
      (d(matrix[0][0]      ) * d(matrix[1][2]      )) - (d(matrix[0][2]      ) * d(matrix[1][0]      ))
  )
  __lowercase							  = (d(matrix[0][0]      ) * d(matrix[1][1]      )) - (
      d(matrix[0][1]      ) * d(matrix[1][0]      )
  )

  # Transpose the cofactor matrix (Adjoint matrix)
  __lowercase							  = array(A__      )
  for i in range(3      ):
   for j in range(3      ):
    __lowercase							  = cofactor_matrix[j][i]

        # Inverse of the matrix using the formula (1/determinant) * adjoint matrix
  __lowercase							  = array(A__      )
  for i in range(3      ):
   for j in range(3      ):
    inverse_matrix[i][j] /= d(A__      )

        # Calculate the inverse of the matrix
  return [[float(d(A__      )      ) or 0.0 for n in row] for row in inverse_matrix]
 raise ValueError('''Please provide a matrix of size 2x2 or 3x3.'''      )

