


'''simple docstring'''






import gc
import unittest

from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_gpu,
    slow,
)

from .test_pipelines_common import ANY




@is_pipeline_test
class 	a       (       unittest.TestCase    ):
 _lowerCAmelCase	   =		MODEL_FOR_MASKED_LM_MAPPING
 _lowerCAmelCase	   =		TF_MODEL_FOR_MASKED_LM_MAPPING
 def 							__UpperCAmelCase						(	self  )   ->							Tuple:
      super().tearDown()
      # clean-up as much as possible GPU memory occupied by PyTorch
      gc.collect()
      if is_torch_available():
           import torch

           torch.cuda.empty_cache()
 @require_tf
 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      _a      =							pipeline(task='fill-mask' ,			model='sshleifer/tiny-distilroberta-base' ,			top_k=2 ,			framework='tf'  )
      _a      =							unmasker('My name is <mask>'  )
      self.assertEqual(
          nested_simplify(__magic_name__ ,			decimals=6  ) ,			[
              {'sequence': 'My name is grouped', 'score': 2.1e-05, 'token': 3_80_15, 'token_str': ' grouped'},
              {'sequence': 'My name is accuser', 'score': 2.1e-05, 'token': 2_55_06, 'token_str': ' accuser'},
          ] ,			)

      _a      =							unmasker('The largest city in France is <mask>'  )
      self.assertEqual(
          nested_simplify(__magic_name__ ,			decimals=6  ) ,			[
              {
                  'sequence': 'The largest city in France is grouped',
                  'score': 2.1e-05,
                  'token': 3_80_15,
                  'token_str': ' grouped',
              },
              {
                  'sequence': 'The largest city in France is accuser',
                  'score': 2.1e-05,
                  'token': 2_55_06,
                  'token_str': ' accuser',
              },
          ] ,			)

      _a      =							unmasker('My name is <mask>' ,			targets=[' Patrick', ' Clara', ' Teven'] ,			top_k=3  )
      self.assertEqual(
          nested_simplify(__magic_name__ ,			decimals=6  ) ,			[
              {'sequence': 'My name is Clara', 'score': 2e-05, 'token': 1_36_06, 'token_str': ' Clara'},
              {'sequence': 'My name is Patrick', 'score': 2e-05, 'token': 34_99, 'token_str': ' Patrick'},
              {'sequence': 'My name is Te', 'score': 1.9e-05, 'token': 29_41, 'token_str': ' Te'},
          ] ,			)
 @require_torch
 def 							__UpperCAmelCase						(	self  )   ->							List[str]:
      _a      =							pipeline(task='fill-mask' ,			model='sshleifer/tiny-distilroberta-base' ,			top_k=2 ,			framework='pt'  )

      _a      =							unmasker('My name is <mask>'  )
      self.assertEqual(
          nested_simplify(__magic_name__ ,			decimals=6  ) ,			[
              {'sequence': 'My name is Maul', 'score': 2.2e-05, 'token': 3_56_76, 'token_str': ' Maul'},
              {'sequence': 'My name isELS', 'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS'},
          ] ,			)

      _a      =							unmasker('The largest city in France is <mask>'  )
      self.assertEqual(
          nested_simplify(__magic_name__ ,			decimals=6  ) ,			[
              {
                  'sequence': 'The largest city in France is Maul',
                  'score': 2.2e-05,
                  'token': 3_56_76,
                  'token_str': ' Maul',
              },
              {'sequence': 'The largest city in France isELS', 'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS'},
          ] ,			)

      _a      =							unmasker('My name is <mask>' ,			targets=[' Patrick', ' Clara', ' Teven'] ,			top_k=3  )
      self.assertEqual(
          nested_simplify(__magic_name__ ,			decimals=6  ) ,			[
              {'sequence': 'My name is Patrick', 'score': 2.1e-05, 'token': 34_99, 'token_str': ' Patrick'},
              {'sequence': 'My name is Te', 'score': 2e-05, 'token': 29_41, 'token_str': ' Te'},
              {'sequence': 'My name is Clara', 'score': 2e-05, 'token': 1_36_06, 'token_str': ' Clara'},
          ] ,			)

      _a      =							unmasker('My name is <mask> <mask>' ,			top_k=2  )

      self.assertEqual(
          nested_simplify(__magic_name__ ,			decimals=6  ) ,			[
              [
                  {
                      'score': 2.2e-05,
                      'token': 3_56_76,
                      'token_str': ' Maul',
                      'sequence': '<s>My name is Maul<mask></s>',
                  },
                  {'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS', 'sequence': '<s>My name isELS<mask></s>'},
              ],
              [
                  {
                      'score': 2.2e-05,
                      'token': 3_56_76,
                      'token_str': ' Maul',
                      'sequence': '<s>My name is<mask> Maul</s>',
                  },
                  {'score': 2.2e-05, 'token': 1_64_16, 'token_str': 'ELS', 'sequence': '<s>My name is<mask>ELS</s>'},
              ],
          ] ,			)
 @require_torch_gpu
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      _a      =							pipeline('fill-mask' ,			model='hf-internal-testing/tiny-random-distilbert' ,			device=0 ,			framework='pt'  )

      # convert model to fp16
      pipe.model.half()

      _a      =							pipe('Paris is the [MASK] of France.'  )
      # We actually don't care about the result, we just want to make sure
      # it works, meaning the float16 tensor got casted back to float32
      # for postprocessing.
      self.assertIsInstance(__magic_name__ ,			__magic_name__  )
 @slow
 @require_torch
 def 							__UpperCAmelCase						(	self  )   ->							Tuple:
      _a      =							pipeline(task='fill-mask' ,			model='distilroberta-base' ,			top_k=2 ,			framework='pt'  )
      self.run_large_test(__magic_name__  )
 @slow
 @require_tf
 def 							__UpperCAmelCase						(	self  )   ->							Union[str, Any]:
      _a      =							pipeline(task='fill-mask' ,			model='distilroberta-base' ,			top_k=2 ,			framework='tf'  )
      self.run_large_test(__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							Optional[int]:
      _a      =							unmasker('My name is <mask>'  )
      self.assertEqual(
          nested_simplify(__magic_name__  ) ,			[
              {'sequence': 'My name is John', 'score': 0.0_0_8, 'token': 6_10, 'token_str': ' John'},
              {'sequence': 'My name is Chris', 'score': 0.0_0_7, 'token': 15_73, 'token_str': ' Chris'},
          ] ,			)
      _a      =							unmasker('The largest city in France is <mask>'  )
      self.assertEqual(
          nested_simplify(__magic_name__  ) ,			[
              {
                  'sequence': 'The largest city in France is Paris',
                  'score': 0.2_5_1,
                  'token': 22_01,
                  'token_str': ' Paris',
              },
              {
                  'sequence': 'The largest city in France is Lyon',
                  'score': 0.2_1_4,
                  'token': 1_27_90,
                  'token_str': ' Lyon',
              },
          ] ,			)

      _a      =							unmasker('My name is <mask>' ,			targets=[' Patrick', ' Clara', ' Teven'] ,			top_k=3  )
      self.assertEqual(
          nested_simplify(__magic_name__  ) ,			[
              {'sequence': 'My name is Patrick', 'score': 0.0_0_5, 'token': 34_99, 'token_str': ' Patrick'},
              {'sequence': 'My name is Clara', 'score': 0.0_0_0, 'token': 1_36_06, 'token_str': ' Clara'},
              {'sequence': 'My name is Te', 'score': 0.0_0_0, 'token': 29_41, 'token_str': ' Te'},
          ] ,			)
 @require_torch
 def 							__UpperCAmelCase						(	self  )   ->							List[Any]:
      _a      =							pipeline(task='fill-mask' ,			model='sshleifer/tiny-distilroberta-base' ,			framework='pt'  )
      _a      =							None
      _a      =							None
      self.run_pipeline_test(__magic_name__ ,			[]  )
 @require_tf
 def 							__UpperCAmelCase						(	self  )   ->							List[str]:
      _a      =							pipeline(task='fill-mask' ,			model='sshleifer/tiny-distilroberta-base' ,			framework='tf'  )
      _a      =							None
      _a      =							None
      self.run_pipeline_test(__magic_name__ ,			[]  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__  )   ->							str:
      if tokenizer is None or tokenizer.mask_token_id is None:
           self.skipTest('The provided tokenizer has no mask token, (probably reformer or wav2vec2)'  )

      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__  )
      _a      =							[
          f'This is another {tokenizer.mask_token} test',
      ]
      return fill_masker, examples
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							str:
      _a      =							fill_masker.tokenizer
      _a      =							fill_masker.model

      _a      =							fill_masker(
          f'This is a {tokenizer.mask_token}' ,			)
      self.assertEqual(
          __magic_name__ ,			[
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
          ] ,			)

      _a      =							fill_masker([f'This is a {tokenizer.mask_token}']  )
      self.assertEqual(
          __magic_name__ ,			[
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
          ] ,			)

      _a      =							fill_masker([f'This is a {tokenizer.mask_token}', f'Another {tokenizer.mask_token} great test.']  )
      self.assertEqual(
          __magic_name__ ,			[
              [
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              ],
              [
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              ],
          ] ,			)

      with self.assertRaises(__magic_name__  ):
           fill_masker([None]  )
      # No mask_token is not supported
      with self.assertRaises(__magic_name__  ):
           fill_masker('This is'  )

      self.run_test_top_k(__magic_name__ ,			__magic_name__  )
      self.run_test_targets(__magic_name__ ,			__magic_name__  )
      self.run_test_top_k_targets(__magic_name__ ,			__magic_name__  )
      self.fill_mask_with_duplicate_targets_and_top_k(__magic_name__ ,			__magic_name__  )
      self.fill_mask_with_multiple_masks(__magic_name__ ,			__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							Tuple:
      _a      =							tokenizer.get_vocab()
      _a      =							sorted(vocab.keys()  )[:2]
      # Pipeline argument
      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__ ,			targets=__magic_name__  )
      _a      =							fill_masker(f'This is a {tokenizer.mask_token}'  )
      self.assertEqual(
          __magic_name__ ,			[
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
          ] ,			)
      _a      =							{vocab[el] for el in targets}
      self.assertEqual({el['token'] for el in outputs} ,			__magic_name__  )
      _a      =							[tokenizer.decode([x]  ) for x in target_ids]
      self.assertEqual({el['token_str'] for el in outputs} ,			set(__magic_name__  )  )

      # Call argument
      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__  )
      _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			targets=__magic_name__  )
      self.assertEqual(
          __magic_name__ ,			[
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
          ] ,			)
      _a      =							{vocab[el] for el in targets}
      self.assertEqual({el['token'] for el in outputs} ,			__magic_name__  )
      _a      =							[tokenizer.decode([x]  ) for x in target_ids]
      self.assertEqual({el['token_str'] for el in outputs} ,			set(__magic_name__  )  )

      # Score equivalence
      _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			targets=__magic_name__  )
      _a      =							[top_mask['token_str'] for top_mask in outputs]
      _a      =							[top_mask['score'] for top_mask in outputs]

      # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
      if set(__magic_name__  ) == set(__magic_name__  ):
           _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			targets=__magic_name__  )
           _a      =							[top_mask['score'] for top_mask in unmasked_targets]
           self.assertEqual(nested_simplify(__magic_name__  ) ,			nested_simplify(__magic_name__  )  )

      # Raises with invalid
      with self.assertRaises(__magic_name__  ):
           _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			targets=[]  )
      # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
      if "" not in tokenizer.get_vocab():
           with self.assertRaises(__magic_name__  ):
                _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			targets=['']  )
           with self.assertRaises(__magic_name__  ):
                _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			targets=''  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							Union[str, Any]:
      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__ ,			top_k=2  )
      _a      =							fill_masker(f'This is a {tokenizer.mask_token}'  )
      self.assertEqual(
          __magic_name__ ,			[
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
          ] ,			)

      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__  )
      _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			top_k=2  )
      self.assertEqual(
          __magic_name__ ,			[
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
          ] ,			)
      self.assertEqual(nested_simplify(__magic_name__  ) ,			nested_simplify(__magic_name__  )  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							int:
      _a      =							tokenizer.get_vocab()
      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__  )

      # top_k=2, ntargets=3
      _a      =							sorted(vocab.keys()  )[:3]
      _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			top_k=2 ,			targets=__magic_name__  )

      # If we use the most probably targets, and filter differently, we should still
      # have the same results
      _a      =							[el['token_str'] for el in sorted(__magic_name__ ,			key=lambda __magic_name__  : x["score"] ,			reverse=__magic_name__  )]
      # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
      if set(__magic_name__  ).issubset(__magic_name__  ):
           _a      =							fill_masker(f'This is a {tokenizer.mask_token}' ,			top_k=3 ,			targets=__magic_name__  )
           # They should yield exactly the same result
           self.assertEqual(nested_simplify(__magic_name__  ) ,			nested_simplify(__magic_name__  )  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							Dict:
      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__  )
      _a      =							tokenizer.get_vocab()
      # String duplicates + id duplicates
      _a      =							sorted(vocab.keys()  )[:3]
      _a      =							[targets[0], targets[1], targets[0], targets[2], targets[1]]
      _a      =							fill_masker(f'My name is {tokenizer.mask_token}' ,			targets=__magic_name__ ,			top_k=10  )

      # The target list contains duplicates, so we can't output more
      # than them
      self.assertEqual(len(__magic_name__  ) ,			3  )




 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							List[str]:
      _a      =							FillMaskPipeline(model=__magic_name__ ,			tokenizer=__magic_name__  )

      _a      =							fill_masker(
          f'This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}' ,			top_k=2  )
      self.assertEqual(
          __magic_name__ ,			[
              [
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              ],
              [
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              ],
              [
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
                  {'sequence': ANY(__magic_name__  ), 'score': ANY(__magic_name__  ), 'token': ANY(__magic_name__  ), 'token_str': ANY(__magic_name__  )},
              ],
          ] ,			)





'''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	   =		42
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		42
 _lowerCAmelCase	   =		42
 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

