


'''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_   :      Optional[int]				    =      logging.get_logger(__name__)

a_   :      List[Any]				    =      list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
a_   :      List[str]				    =      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




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





class 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		"""train"""
 _lowerCAmelCase	   =		"""dev"""





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

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

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

                _a      =							time.time()
                torch.save(
                    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples} ,			__magic_name__ ,			)
                # ^ 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  )   ->							List[Any]:
      return len(self.features  )




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

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

      _a      =							{
          '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:
           _a      =							torch.tensor(feature.start_position ,			dtype=torch.long  )
           _a      =							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 sys import maxsize
from typing import Generic, TypeVar

a_   :      Optional[Any]				    =      TypeVar("T")






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     return (position - 1) // 2






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     return (2 * position) + 1






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     return (2 * position) + 2




class 	a       (       Generic[T]    ):
 def __init__(	self  )   ->							None:
      _a      =							[]
      _a      =							{}
      _a      =							0
 def __len__(	self  )   ->							int:
      return self.elements
 def __repr__(	self  )   ->							str:
      return str(self.heap  )
 def 							__UpperCAmelCase						(	self  )   ->							bool:
      # Check if the priority queue is empty
      return self.elements == 0
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Add an element with given priority to the queue
      self.heap.append((elem, weight)  )
      _a      =							self.elements
      self.elements += 1
      self._bubble_up(__magic_name__  )
 def 							__UpperCAmelCase						(	self  )   ->							T:
      # Remove and return the element with lowest weight (highest priority)
      if self.elements > 1:
           self._swap_nodes(0 ,			self.elements - 1  )
      _a ,				_a      =							self.heap.pop()
      del self.position_map[elem]
      self.elements -= 1
      if self.elements > 0:
           _a ,				_a      =							self.heap[0]
           self._bubble_down(__magic_name__  )
      return elem
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Update the weight of the given key
      _a      =							self.position_map[elem]
      _a      =							(elem, weight)
      if position > 0:
           _a      =							get_parent_position(__magic_name__  )
           _a ,				_a      =							self.heap[parent_position]
           if parent_weight > weight:
                self._bubble_up(__magic_name__  )
           else:
                self._bubble_down(__magic_name__  )
      else:
           self._bubble_down(__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							None:
      # Place a node at the proper position (upward movement) [to be used internally
      # only]
      _a      =							self.position_map[elem]
      if curr_pos == 0:
           return None
      _a      =							get_parent_position(__magic_name__  )
      _a ,				_a      =							self.heap[curr_pos]
      _a ,				_a      =							self.heap[parent_position]
      if parent_weight > weight:
           self._swap_nodes(__magic_name__ ,			__magic_name__  )
           return self._bubble_up(__magic_name__  )
      return None
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							None:
      # Place a node at the proper position (downward movement) [to be used
      # internally only]
      _a      =							self.position_map[elem]
      _a ,				_a      =							self.heap[curr_pos]
      _a      =							get_child_left_position(__magic_name__  )
      _a      =							get_child_right_position(__magic_name__  )
      if child_left_position < self.elements and child_right_position < self.elements:
           _a ,				_a      =							self.heap[child_left_position]
           _a ,				_a      =							self.heap[child_right_position]
           if child_right_weight < child_left_weight and child_right_weight < weight:
                self._swap_nodes(__magic_name__ ,			__magic_name__  )
                return self._bubble_down(__magic_name__  )
      if child_left_position < self.elements:
           _a ,				_a      =							self.heap[child_left_position]
           if child_left_weight < weight:
                self._swap_nodes(__magic_name__ ,			__magic_name__  )
                return self._bubble_down(__magic_name__  )
      else:
           return None
      if child_right_position < self.elements:
           _a ,				_a      =							self.heap[child_right_position]
           if child_right_weight < weight:
                self._swap_nodes(__magic_name__ ,			__magic_name__  )
                return self._bubble_down(__magic_name__  )
      return None




 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Swap the nodes at the given positions
      _a      =							self.heap[nodea_pos][0]
      _a      =							self.heap[nodea_pos][0]
      _a ,				_a      =							(
          self.heap[nodea_pos],
          self.heap[nodea_pos],
      )
      _a      =							nodea_pos
      _a      =							nodea_pos





class 	a       (       Generic[T]    ):
 def __init__(	self  )   ->							None:
      _a      =							{}
      _a      =							0
 def __repr__(	self  )   ->							str:
      return str(self.connections  )
 def __len__(	self  )   ->							int:
      return self.nodes
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							None:
      # Add a node in the graph if it is not in the graph
      if node not in self.connections:
           _a      =							{}
           self.nodes += 1




 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Add an edge between 2 nodes in the graph
      self.add_node(__magic_name__  )
      self.add_node(__magic_name__  )
      _a      =							weight
      _a      =							weight






def 		_A			(lowerCAmelCase__					:GraphUndirectedWeighted[T]			,  )				->					tuple[dict[T, int], dict[T, T | None]]:




     '''simple docstring'''



     _a      =							{node: maxsize for node in graph.connections}
     _a      =							{node: None for node in graph.connections}

     _a      =							MinPriorityQueue()
     for node, weight in dist.items():
          priority_queue.push(lowerCAmelCase__			,  lowerCAmelCase__						)

     if priority_queue.is_empty():
          return dist, parent

     # initialization
     _a      =							priority_queue.extract_min()
     _a      =							0
     for neighbour in graph.connections[node]:
          if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
               _a      =							dist[node] + graph.connections[node][neighbour]
               priority_queue.update_key(lowerCAmelCase__			,  dist[neighbour]						)
               _a      =							node

    # running prim's algorithm
     while not priority_queue.is_empty():
          _a      =							priority_queue.extract_min()
          for neighbour in graph.connections[node]:
               if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
                    _a      =							dist[node] + graph.connections[node][neighbour]
                    priority_queue.update_key(lowerCAmelCase__			,  dist[neighbour]						)
                    _a      =							node
     return dist, parent

