


import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
 from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"):
 a_   :      Any				    =      True
 from torch.cuda.amp import autocast

a_   :      Optional[Any]				    =      logging.getLogger(__name__)






def 		_A			(lowerCAmelCase__					:Dict=None			,  lowerCAmelCase__					:Tuple=None						)				->					int:




     '''simple docstring'''



     return field(default_factory=lambda: default			,  metadata=lowerCAmelCase__						)




@dataclass
class 	a       :
 _lowerCAmelCase	   =		field(
     metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}    )
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}					,			)
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}    )
 _lowerCAmelCase	   =		field(
     default=0.1					,			metadata={"""help""": """The dropout ratio for the attention probabilities."""}    )
 _lowerCAmelCase	   =		field(
     default=0.1					,			metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""}    )
 _lowerCAmelCase	   =		field(
     default=0.1					,			metadata={
         """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."""
     }					,			)
 _lowerCAmelCase	   =		field(
     default=0.1					,			metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""}					,			)
 _lowerCAmelCase	   =		field(
     default=0.05					,			metadata={
         """help""": (
             """Propability of each feature vector along the time axis to be chosen as the start of the vector"""
             """span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"""
             """vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``."""
         )
     }					,			)
 _lowerCAmelCase	   =		field(default=0.0					,			metadata={"""help""": """The LayerDrop probability."""}    )





@dataclass
class 	a       :
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}    )
 _lowerCAmelCase	   =		field(
     default="""train+validation"""					,			metadata={
         """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
     }					,			)
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}    )
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """The number of processes to use for the preprocessing."""}					,			)
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={
         """help""": (
             """For debugging purposes or quicker training, truncate the number of training examples to this """
             """value if set."""
         )
     }					,			)
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={
         """help""": (
             """For debugging purposes or quicker training, truncate the number of validation examples to this """
             """value if set."""
         )
     }					,			)
 _lowerCAmelCase	   =		list_field(
     default=[""",""", """?""", """.""", """!""", """-""", """;""", """:""", """\"\"""", """%""", """'""", """\"""", """�"""]					,			metadata={"""help""": """A list of characters to remove from the transcripts."""}					,			)





@dataclass
class 	a       :
 _lowerCAmelCase	   =		4_2
 _lowerCAmelCase	   =		True
 _lowerCAmelCase	   =		None
 _lowerCAmelCase	   =		None
 _lowerCAmelCase	   =		None
 _lowerCAmelCase	   =		None
 def __call__(	self ,			__magic_name__  )   ->							Dict[str, torch.Tensor]:
      # split inputs and labels since they have to be of different lenghts and need
      # different padding methods
      _a      =							[{'input_values': feature['input_values']} for feature in features]
      _a      =							[{'input_ids': feature['labels']} for feature in features]

      _a      =							self.processor.pad(
          __magic_name__ ,			padding=self.padding ,			max_length=self.max_length ,			pad_to_multiple_of=self.pad_to_multiple_of ,			return_tensors='pt' ,			)
      _a      =							self.processor.pad(
          labels=__magic_name__ ,			padding=self.padding ,			max_length=self.max_length_labels ,			pad_to_multiple_of=self.pad_to_multiple_of_labels ,			return_tensors='pt' ,			)

      # replace padding with -100 to ignore loss correctly
      _a      =							labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1  ) ,			-1_00  )

      _a      =							labels

      return batch





class 	a       (       _SCREAMING_SNAKE_CASE    ):
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							torch.Tensor:
      model.train()
      _a      =							self._prepare_inputs(__magic_name__  )

      if self.use_amp:
           with autocast():
                _a      =							self.compute_loss(__magic_name__ ,			__magic_name__  )
      else:
           _a      =							self.compute_loss(__magic_name__ ,			__magic_name__  )

      if self.args.n_gpu > 1:
           if model.module.config.ctc_loss_reduction == "mean":
                _a      =							loss.mean()
           elif model.module.config.ctc_loss_reduction == "sum":
                _a      =							loss.sum() / (inputs['labels'] >= 0).sum()
           else:
                raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'  )

      if self.args.gradient_accumulation_steps > 1:
           _a      =							loss / self.args.gradient_accumulation_steps

      if self.use_amp:
           self.scaler.scale(__magic_name__  ).backward()
      elif self.use_apex:
           with amp.scale_loss(__magic_name__ ,			self.optimizer  ) as scaled_loss:
                scaled_loss.backward()
      elif self.deepspeed:
           self.deepspeed.backward(__magic_name__  )
      else:
           loss.backward()

      return loss.detach()






def 		_A			()				->					int:




     '''simple docstring'''



     _a      =							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
     if len(sys.argv						) == 2 and sys.argv[1].endswith('.json'						):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          _a ,				_a ,				_a      =							parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
     else:
          _a ,				_a ,				_a      =							parser.parse_args_into_dataclasses()

     # Detecting last checkpoint.
     _a      =							None
     if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
          _a      =							get_last_checkpoint(training_args.output_dir						)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir						)						) > 0:
               raise ValueError(
                   f'Output directory ({training_args.output_dir}) already exists and is not empty. '
                   'Use --overwrite_output_dir to overcome.'						)
          elif last_checkpoint is not None:
               logger.info(
                   f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
                   'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'						)

    # Setup logging
     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'			,  datefmt='%m/%d/%Y %H:%M:%S'			,  handlers=[logging.StreamHandler(sys.stdout						)]			,  )
     logger.setLevel(logging.INFO if is_main_process(training_args.local_rank						) else logging.WARN						)

     # Log on each process the small summary:
     logger.warning(
         f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
         + f'distributed training: {bool(training_args.local_rank != -1						)}, 16-bits training: {training_args.fpaa}'						)
     # Set the verbosity to info of the Transformers logger (on main process only):
     if is_main_process(training_args.local_rank						):
          transformers.utils.logging.set_verbosity_info()
     logger.info('Training/evaluation parameters %s'			,  lowerCAmelCase__						)

     # Set seed before initializing model.
     set_seed(training_args.seed						)

     # Get the datasets:
     _a      =							datasets.load_dataset(
         'common_voice'			,  data_args.dataset_config_name			,  split=data_args.train_split_name						)
     _a      =							datasets.load_dataset('common_voice'			,  data_args.dataset_config_name			,  split='test'						)

     # Create and save tokenizer
     _a      =							f'[{"".join(data_args.chars_to_ignore						)}]'

     def remove_special_characters(lowerCAmelCase__					:List[str]						):
          _a      =							re.sub(lowerCAmelCase__			,  ''			,  batch['sentence']						).lower() + ' '
          return batch

     _a      =							train_dataset.map(lowerCAmelCase__			,  remove_columns=['sentence']						)
     _a      =							eval_dataset.map(lowerCAmelCase__			,  remove_columns=['sentence']						)

     def extract_all_chars(lowerCAmelCase__					:Union[str, Any]						):
          _a      =							' '.join(batch['text']						)
          _a      =							list(set(lowerCAmelCase__						)						)
          return {"vocab": [vocab], "all_text": [all_text]}

     _a      =							train_dataset.map(
         lowerCAmelCase__			,  batched=lowerCAmelCase__			,  batch_size=-1			,  keep_in_memory=lowerCAmelCase__			,  remove_columns=train_dataset.column_names			,  )
     _a      =							train_dataset.map(
         lowerCAmelCase__			,  batched=lowerCAmelCase__			,  batch_size=-1			,  keep_in_memory=lowerCAmelCase__			,  remove_columns=eval_dataset.column_names			,  )

     _a      =							list(set(vocab_train['vocab'][0]						) | set(vocab_test['vocab'][0]						)						)
     _a      =							{v: k for k, v in enumerate(lowerCAmelCase__						)}
     _a      =							vocab_dict[' ']
     del vocab_dict[" "]
     _a      =							len(lowerCAmelCase__						)
     _a      =							len(lowerCAmelCase__						)

     with open('vocab.json'			,  'w'						) as vocab_file:
          json.dump(lowerCAmelCase__			,  lowerCAmelCase__						)

     # Load pretrained model and tokenizer
     #
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.
     _a      =							WavaVecaCTCTokenizer(
         'vocab.json'			,  unk_token='[UNK]'			,  pad_token='[PAD]'			,  word_delimiter_token='|'			,  )
     _a      =							WavaVecaFeatureExtractor(
         feature_size=1			,  sampling_rate=1_60_00			,  padding_value=0.0			,  do_normalize=lowerCAmelCase__			,  return_attention_mask=lowerCAmelCase__						)
     _a      =							WavaVecaProcessor(feature_extractor=lowerCAmelCase__			,  tokenizer=lowerCAmelCase__						)
     _a      =							WavaVecaForCTC.from_pretrained(
         model_args.model_name_or_path			,  cache_dir=model_args.cache_dir			,  activation_dropout=model_args.activation_dropout			,  attention_dropout=model_args.attention_dropout			,  hidden_dropout=model_args.hidden_dropout			,  feat_proj_dropout=model_args.feat_proj_dropout			,  mask_time_prob=model_args.mask_time_prob			,  gradient_checkpointing=training_args.gradient_checkpointing			,  layerdrop=model_args.layerdrop			,  ctc_loss_reduction='mean'			,  pad_token_id=processor.tokenizer.pad_token_id			,  vocab_size=len(processor.tokenizer						)			,  )

     if data_args.max_train_samples is not None:
          _a      =							min(len(lowerCAmelCase__						)			,  data_args.max_train_samples						)
          _a      =							train_dataset.select(range(lowerCAmelCase__						)						)

     if data_args.max_val_samples is not None:
          _a      =							eval_dataset.select(range(data_args.max_val_samples						)						)

     _a      =							torchaudio.transforms.Resample(4_80_00			,  1_60_00						)

     # Preprocessing the datasets.
     # We need to read the aduio files as arrays and tokenize the targets.
     def speech_file_to_array_fn(lowerCAmelCase__					:Optional[int]						):
          _a ,				_a      =							torchaudio.load(batch['path']						)
          _a      =							resampler(lowerCAmelCase__						).squeeze().numpy()
          _a      =							1_60_00
          _a      =							batch['text']
          return batch

     _a      =							train_dataset.map(
         lowerCAmelCase__			,  remove_columns=train_dataset.column_names			,  num_proc=data_args.preprocessing_num_workers			,  )
     _a      =							eval_dataset.map(
         lowerCAmelCase__			,  remove_columns=eval_dataset.column_names			,  num_proc=data_args.preprocessing_num_workers			,  )

     def prepare_dataset(lowerCAmelCase__					:Optional[int]						):
          # check that all files have the correct sampling rate
          assert (
              len(set(batch['sampling_rate']						)						) == 1
          ), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'

          _a      =							processor(
              audio=batch['speech']			,  text=batch['target_text']			,  sampling_rate=batch['sampling_rate'][0]						)
          batch.update(lowerCAmelCase__						)
          return batch

     _a      =							train_dataset.map(
         lowerCAmelCase__			,  remove_columns=train_dataset.column_names			,  batch_size=training_args.per_device_train_batch_size			,  batched=lowerCAmelCase__			,  num_proc=data_args.preprocessing_num_workers			,  )
     _a      =							eval_dataset.map(
         lowerCAmelCase__			,  remove_columns=eval_dataset.column_names			,  batch_size=training_args.per_device_train_batch_size			,  batched=lowerCAmelCase__			,  num_proc=data_args.preprocessing_num_workers			,  )

     # Metric
     _a      =							datasets.load_metric('wer'						)

     def compute_metrics(lowerCAmelCase__					:Dict						):
          _a      =							pred.predictions
          _a      =							np.argmax(lowerCAmelCase__			,  axis=-1						)

          _a      =							processor.tokenizer.pad_token_id

          _a      =							processor.batch_decode(lowerCAmelCase__						)
          # we do not want to group tokens when computing the metrics
          _a      =							processor.batch_decode(pred.label_ids			,  group_tokens=lowerCAmelCase__						)

          _a      =							wer_metric.compute(predictions=lowerCAmelCase__			,  references=lowerCAmelCase__						)

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     # Data collator
     _a      =							DataCollatorCTCWithPadding(processor=lowerCAmelCase__			,  padding=lowerCAmelCase__						)

     # Initialize our Trainer
     _a      =							CTCTrainer(
         model=lowerCAmelCase__			,  data_collator=lowerCAmelCase__			,  args=lowerCAmelCase__			,  compute_metrics=lowerCAmelCase__			,  train_dataset=train_dataset if training_args.do_train else None			,  eval_dataset=eval_dataset if training_args.do_eval else None			,  tokenizer=processor.feature_extractor			,  )

     # Training
     if training_args.do_train:
          if last_checkpoint is not None:
               _a      =							last_checkpoint
          elif os.path.isdir(model_args.model_name_or_path						):
               _a      =							model_args.model_name_or_path
          else:
               _a      =							None

          # Save the feature_extractor and the tokenizer
          if is_main_process(training_args.local_rank						):
               processor.save_pretrained(training_args.output_dir						)

          _a      =							trainer.train(resume_from_checkpoint=lowerCAmelCase__						)
          trainer.save_model()

          _a      =							train_result.metrics
          _a      =							(
              data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase__						)
          )
          _a      =							min(lowerCAmelCase__			,  len(lowerCAmelCase__						)						)

          trainer.log_metrics('train'			,  lowerCAmelCase__						)
          trainer.save_metrics('train'			,  lowerCAmelCase__						)
          trainer.save_state()

     # Evaluation
     _a      =							{}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'						)
          _a      =							trainer.evaluate()
          _a      =							data_args.max_val_samples if data_args.max_val_samples is not None else len(lowerCAmelCase__						)
          _a      =							min(lowerCAmelCase__			,  len(lowerCAmelCase__						)						)

          trainer.log_metrics('eval'			,  lowerCAmelCase__						)
          trainer.save_metrics('eval'			,  lowerCAmelCase__						)

     return results


if __name__ == "__main__":
 main()





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

