


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


lowercase_			       =      logging.get_logger(__name__)

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


@dataclass
class 			A_   :




      '''simple docstring'''


      __snake_case   			=  field(
          default=A__   , metadata={"""help""": """Model type selected in the list: """ + """, """.join(A__       )}       )
      __snake_case   			=  field(
          default=A__   , metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}       )
      __snake_case   			=  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."""
              )
          }   , )
      __snake_case   			=  field(
          default=128   , metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}   , )
      __snake_case   			=  field(
          default=64   , metadata={
              """help""": (
                  """The maximum number of tokens for the question. Questions longer than this will """
                  """be truncated to this length."""
              )
          }   , )
      __snake_case   			=  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."""
              )
          }   , )
      __snake_case   			=  field(
          default=A__   , metadata={"""help""": """Overwrite the cached training and evaluation sets"""}       )
      __snake_case   			=  field(
          default=A__   , 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=20   , 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 			A_   (			A__       ):




      '''simple docstring'''


      __snake_case   			=  """train"""
      __snake_case   			=  """dev"""



class 			A_   (			A__       ):




      '''simple docstring'''


      __snake_case   			=  42
      __snake_case   			=  42
      __snake_case   			=  42
      __snake_case   			=  42




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

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

         __lowerCamelCase						:				List[Any]						   =		squad_convert_examples_to_features(
             examples=self.examples		, tokenizer=UpperCamelCase_		, 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=UpperCamelCase_		, )

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

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

       __lowerCamelCase						:				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:
        __lowerCamelCase						:				Any						   =		torch.tensor(feature.start_position		, dtype=torch.long							)
        __lowerCamelCase						:				List[Any]						   =		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

import math
import random
from collections.abc import Collection
from typing import overload
class   lowercase      :

		"""simple docstring"""

		def __init__(						self       ,  UpperCamelCase_ = None				):

							'''simple docstring'''


							if components is None:
												UpperCamelCase__  :List[Any]				   =					[]
							UpperCamelCase__  :Optional[Any]				   =					list(UpperCamelCase_				)




		def __len__(						self				):

							'''simple docstring'''


							return len(self.__components				)




		def __str__(						self				):

							'''simple docstring'''


							return "(" + ",".join(map(UpperCamelCase_       ,  self.__components				)				) + ")"




		def __add__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :Any				   =					len(self				)
							if size == len(UpperCamelCase_				):
												UpperCamelCase__  :Dict				   =					[self.__components[i] + other.component(UpperCamelCase_				) for i in range(UpperCamelCase_				)]
												return Vector(UpperCamelCase_				)
							else:
												raise Exception('''must have the same size'''				)




		def __sub__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :Optional[Any]				   =					len(self				)
							if size == len(UpperCamelCase_				):
												UpperCamelCase__  :List[str]				   =					[self.__components[i] - other.component(UpperCamelCase_				) for i in range(UpperCamelCase_				)]
												return Vector(UpperCamelCase_				)
							else:  # error case
												raise Exception('''must have the same size'''				)




		@overload
		def __mul__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							...




		@overload
		def __mul__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							...




		def __mul__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							if isinstance(UpperCamelCase_       ,  (float, int)				):
												UpperCamelCase__  :Optional[Any]				   =					[c * other for c in self.__components]
												return Vector(UpperCamelCase_				)
							elif isinstance(UpperCamelCase_       ,  UpperCamelCase_				) and len(self				) == len(UpperCamelCase_				):
												UpperCamelCase__  :Optional[int]				   =					len(self				)
												UpperCamelCase__  :List[Any]				   =					[self.__components[i] * other.component(UpperCamelCase_				) for i in range(UpperCamelCase_				)]
												return sum(UpperCamelCase_				)
							else:  # error case
												raise Exception('''invalid operand!'''				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							return Vector(self.__components				)




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							if isinstance(UpperCamelCase_       ,  UpperCamelCase_				) and -len(self.__components				) <= i < len(self.__components				):
												return self.__components[i]
							else:
												raise Exception('''index out of range'''				)




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							assert -len(self.__components				) <= pos < len(self.__components				)
							UpperCamelCase__  :Optional[int]				   =					value




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							if len(self.__components				) == 0:
												raise Exception('''Vector is empty'''				)
							UpperCamelCase__  :List[str]				   =					[c**2 for c in self.__components]
							return math.sqrt(sum(UpperCamelCase_				)				)




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_ = False				):

							'''simple docstring'''


							UpperCamelCase__  :List[Any]				   =					self * other
							UpperCamelCase__  :Optional[int]				   =					self.euclidean_length() * other.euclidean_length()
							if deg:
												return math.degrees(math.acos(num / den				)				)
							else:
												return math.acos(num / den				)



def      a (     __a  )    ->      Vector:



					'''simple docstring'''






					assert isinstance(__a					,   __a  )
					return Vector([0] * dimension  )


def      a (     __a					,   __a  )    ->      Vector:



					'''simple docstring'''






					assert isinstance(__a					,   __a  ) and (isinstance(__a					,   __a  ))
					UpperCamelCase__  :str				   =					[0] * dimension
					UpperCamelCase__  :Tuple				   =					1
					return Vector(__a  )


def      a (     __a					,   __a					,   __a  )    ->      Vector:



					'''simple docstring'''






					assert (
					    isinstance(__a					,   __a  )
					    and isinstance(__a					,   __a  )
					    and (isinstance(__a					,   (int, float)  ))
					)
					return x * scalar + y


def      a (     __a					,   __a					,   __a  )    ->      Vector:



					'''simple docstring'''






					random.seed(__a  )
					UpperCamelCase__  :Optional[Any]				   =					[random.randint(__a					,   __a  ) for _ in range(__a  )]
					return Vector(__a  )
class   lowercase      :

		"""simple docstring"""

		def __init__(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							UpperCamelCase__  :int				   =					matrix
							UpperCamelCase__  :Union[str, Any]				   =					w
							UpperCamelCase__  :Optional[int]				   =					h




		def __str__(						self				):

							'''simple docstring'''


							UpperCamelCase__  :Dict				   =					''''''
							for i in range(self.__height				):
												ans += "|"
												for j in range(self.__width				):
																	if j < self.__width - 1:
																						ans += str(self.__matrix[i][j]				) + ","
																	else:
																						ans += str(self.__matrix[i][j]				) + "|\n"
							return ans




		def __add__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							if self.__width == other.width() and self.__height == other.height():
												UpperCamelCase__  :int				   =					[]
												for i in range(self.__height				):
																	UpperCamelCase__  :int				   =					[
																	    self.__matrix[i][j] + other.component(UpperCamelCase_       ,  UpperCamelCase_				)
																	    for j in range(self.__width				)
																	]
																	matrix.append(UpperCamelCase_				)
												return Matrix(UpperCamelCase_       ,  self.__width       ,  self.__height				)
							else:
												raise Exception('''matrix must have the same dimension!'''				)




		def __sub__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							if self.__width == other.width() and self.__height == other.height():
												UpperCamelCase__  :Optional[Any]				   =					[]
												for i in range(self.__height				):
																	UpperCamelCase__  :Optional[int]				   =					[
																	    self.__matrix[i][j] - other.component(UpperCamelCase_       ,  UpperCamelCase_				)
																	    for j in range(self.__width				)
																	]
																	matrix.append(UpperCamelCase_				)
												return Matrix(UpperCamelCase_       ,  self.__width       ,  self.__height				)
							else:
												raise Exception('''matrices must have the same dimension!'''				)




		@overload
		def __mul__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							...




		@overload
		def __mul__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							...




		def __mul__(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							if isinstance(UpperCamelCase_       ,  UpperCamelCase_				):  # matrix-vector
												if len(UpperCamelCase_				) == self.__width:
																	UpperCamelCase__  :Any				   =					zero_vector(self.__height				)
																	for i in range(self.__height				):
																						UpperCamelCase__  :Any				   =					[
																						    self.__matrix[i][j] * other.component(UpperCamelCase_				)
																						    for j in range(self.__width				)
																						]
																						ans.change_component(UpperCamelCase_       ,  sum(UpperCamelCase_				)				)
																	return ans
												else:
																	raise Exception(
																	    '''vector must have the same size as the '''
																	    '''number of columns of the matrix!'''				)
							elif isinstance(UpperCamelCase_       ,  (int, float)				):  # matrix-scalar
												UpperCamelCase__  :Union[str, Any]				   =					[
												    [self.__matrix[i][j] * other for j in range(self.__width				)]
												    for i in range(self.__height				)
												]
												return Matrix(UpperCamelCase_       ,  self.__width       ,  self.__height				)
							return None




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							return self.__height




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							return self.__width




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							if 0 <= x < self.__height and 0 <= y < self.__width:
												return self.__matrix[x][y]
							else:
												raise Exception('''change_component: indices out of bounds'''				)




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							if 0 <= x < self.__height and 0 <= y < self.__width:
												UpperCamelCase__  :Tuple				   =					value
							else:
												raise Exception('''change_component: indices out of bounds'''				)




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							if self.__height != self.__width:
												raise Exception('''Matrix is not square'''				)
							UpperCamelCase__  :str				   =					self.__matrix[:x] + self.__matrix[x + 1 :]
							for i in range(len(UpperCamelCase_				)				):
												UpperCamelCase__  :Union[str, Any]				   =					minor[i][:y] + minor[i][y + 1 :]
							return Matrix(UpperCamelCase_       ,  self.__width - 1       ,  self.__height - 1				).determinant()




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_       ,  UpperCamelCase_				):

							'''simple docstring'''


							if self.__height != self.__width:
												raise Exception('''Matrix is not square'''				)
							if 0 <= x < self.__height and 0 <= y < self.__width:
												return (-1) ** (x + y) * self.minor(UpperCamelCase_       ,  UpperCamelCase_				)
							else:
												raise Exception('''Indices out of bounds'''				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							if self.__height != self.__width:
												raise Exception('''Matrix is not square'''				)
							if self.__height < 1:
												raise Exception('''Matrix has no element'''				)
							elif self.__height == 1:
												return self.__matrix[0][0]
							elif self.__height == 2:
												return (
												    self.__matrix[0][0] * self.__matrix[1][1]
												    - self.__matrix[0][1] * self.__matrix[1][0]
												)
							else:
												UpperCamelCase__  :Optional[Any]				   =					[
												    self.__matrix[0][y] * self.cofactor(0       ,  UpperCamelCase_				) for y in range(self.__width				)
												]
												return sum(UpperCamelCase_				)



def      a (     __a  )    ->      Matrix:



					'''simple docstring'''






					UpperCamelCase__  :list[list[float]]				   =					[[0] * n for _ in range(__a  )]
					return Matrix(__a					,   __a					,   __a  )







def      a (     __a					,   __a					,   __a					,   __a  )    ->      Matrix:



					'''simple docstring'''






					random.seed(__a  )
					UpperCamelCase__  :list[list[float]]				   =					[
					    [random.randint(__a					,   __a  ) for _ in range(__a  )] for _ in range(__a  )
					]
					return Matrix(__a					,   __a					,   __a  )