



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


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







 __lowerCamelCase       :			str		=			field(
     default=A  ,  metadata={'help': 'Model type selected in the list: ' + ', '.join(A		)}		)
 __lowerCamelCase       :			str		=			field(
     default=A  ,  metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'}		)
 __lowerCamelCase       :			int		=			field(
     default=128  ,  metadata={
         'help': (
             'The maximum total input sequence length after tokenization. Sequences longer '
             'than this will be truncated, sequences shorter will be padded.'
         )
     }  ,  )
 __lowerCamelCase       :			int		=			field(
     default=128  ,  metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}  ,  )
 __lowerCamelCase       :			int		=			field(
     default=64  ,  metadata={
         'help': (
             'The maximum number of tokens for the question. Questions longer than this will '
             'be truncated to this length.'
         )
     }  ,  )
 __lowerCamelCase       :			int		=			field(
     default=30  ,  metadata={
         'help': (
             'The maximum length of an answer that can be generated. This is needed because the start '
             'and end predictions are not conditioned on one another.'
         )
     }  ,  )
 __lowerCamelCase       :			bool		=			field(
     default=A  ,  metadata={'help': 'Overwrite the cached training and evaluation sets'}		)
 __lowerCamelCase       :			bool		=			field(
     default=A  ,  metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'}		)
 __lowerCamelCase       :			float		=			field(
     default=0.0  ,  metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}		)
 __lowerCamelCase       :			int		=			field(
     default=20  ,  metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}		)
 __lowerCamelCase       :			int		=			field(
     default=0  ,  metadata={
         'help': (
             'language id of input for language-specific xlm models (see'
             ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
         )
     }  ,  )
 __lowerCamelCase       :			int		=			field(default=1  ,  metadata={'help': 'multiple threads for converting example to features'}		)






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			int		=			'train'
 __lowerCamelCase       :			Union[str, Any]		=			'dev'






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			SquadDataTrainingArguments
 __lowerCamelCase       :			List[SquadFeatures]
 __lowerCamelCase       :			Split
 __lowerCamelCase       :			bool



 def __init__(self					,  A					,  A					,  A = None					,  A = Split.train					,  A = False					,  A = None					,  A = "pt"					,  )       ->	int:


      """simple docstring"""



      _a           =    args
      _a           =    is_language_sensitive
      _a           =    SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
      if isinstance(A					,  A			):
           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(A			):
           if os.path.exists(A			) and not args.overwrite_cache:
                _a           =    time.time()
                _a           =    torch.load(A			)

                # 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'''					,  A			)
                _a           =    self.old_features.get('''examples'''					,  A			)
                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=A					,  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=A					,  )

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


      """simple docstring"""



      return len(self.features			)



 def __getitem__(self					,  A			)       ->	Dict[str, torch.Tensor]:


      """simple docstring"""



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





import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel






class __A     :



 '''simple docstring'''







 def __init__(self					,  A					,  A=13					,  A=7					,  A=True					,  A=True					,  A=False					,  A=True					,  A=99					,  A=32					,  A=5					,  A=4					,  A=37					,  A="gelu"					,  A=0.1					,  A=0.1					,  A=512					,  A=16					,  A=2					,  A=0.02					,  A=3					,  A=4					,  A=None					,  )       ->	str:


      """simple docstring"""



      _a           =    parent
      _a           =    batch_size
      _a           =    seq_length
      _a           =    is_training
      _a           =    use_input_mask
      _a           =    use_token_type_ids
      _a           =    use_labels
      _a           =    vocab_size
      _a           =    hidden_size
      _a           =    num_hidden_layers
      _a           =    num_attention_heads
      _a           =    intermediate_size
      _a           =    hidden_act
      _a           =    hidden_dropout_prob
      _a           =    attention_probs_dropout_prob
      _a           =    max_position_embeddings
      _a           =    type_vocab_size
      _a           =    type_sequence_label_size
      _a           =    initializer_range
      _a           =    num_labels
      _a           =    num_choices
      _a           =    scope



 def    a__    (self			)       ->	List[str]:


      """simple docstring"""



      _a           =    ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size			)

      _a           =    None
      if self.use_input_mask:
           _a           =    random_attention_mask([self.batch_size, self.seq_length]			)

      _a           =    None
      if self.use_token_type_ids:
           _a           =    ids_tensor([self.batch_size, self.seq_length]					,  self.type_vocab_size			)

      _a           =    None
      _a           =    None
      _a           =    None
      if self.use_labels:
           _a           =    ids_tensor([self.batch_size]					,  self.type_sequence_label_size			)
           _a           =    ids_tensor([self.batch_size, self.seq_length]					,  self.num_labels			)
           _a           =    ids_tensor([self.batch_size]					,  self.num_choices			)

      _a           =    self.get_config()

      return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



 def    a__    (self			)       ->	Optional[int]:


      """simple docstring"""



      return OpenLlamaConfig(
          vocab_size=self.vocab_size					,  hidden_size=self.hidden_size					,  num_hidden_layers=self.num_hidden_layers					,  num_attention_heads=self.num_attention_heads					,  intermediate_size=self.intermediate_size					,  hidden_act=self.hidden_act					,  hidden_dropout_prob=self.hidden_dropout_prob					,  attention_probs_dropout_prob=self.attention_probs_dropout_prob					,  max_position_embeddings=self.max_position_embeddings					,  type_vocab_size=self.type_vocab_size					,  is_decoder=A					,  initializer_range=self.initializer_range					,  use_stable_embedding=A					,  )



 def    a__    (self					,  A					,  A					,  A					,  A					,  A					,  A					,  A			)       ->	Any:


      """simple docstring"""



      _a           =    OpenLlamaModel(config=A			)
      model.to(A			)
      model.eval()
      _a           =    model(A					,  attention_mask=A			)
      _a           =    model(A			)
      self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size)			)



 def    a__    (self					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  )       ->	Any:


      """simple docstring"""



      _a           =    True
      _a           =    OpenLlamaModel(A			)
      model.to(A			)
      model.eval()
      _a           =    model(
          A					,  attention_mask=A					,  encoder_hidden_states=A					,  encoder_attention_mask=A					,  )
      _a           =    model(
          A					,  attention_mask=A					,  encoder_hidden_states=A					,  )
      _a           =    model(A					,  attention_mask=A			)
      self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size)			)



 def    a__    (self					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  )       ->	Tuple:


      """simple docstring"""



      _a           =    OpenLlamaForCausalLM(config=A			)
      model.to(A			)
      model.eval()
      _a           =    model(A					,  attention_mask=A					,  labels=A			)
      self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.vocab_size)			)



 def    a__    (self					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  A					,  )       ->	Dict:


      """simple docstring"""



      _a           =    True
      _a           =    True
      _a           =    OpenLlamaForCausalLM(config=A			)
      model.to(A			)
      model.eval()

      # first forward pass
      _a           =    model(
          A					,  attention_mask=A					,  encoder_hidden_states=A					,  encoder_attention_mask=A					,  use_cache=A					,  )
      _a           =    outputs.past_key_values

      # create hypothetical multiple next token and extent to next_input_ids
      _a           =    ids_tensor((self.batch_size, 3)					,  config.vocab_size			)
      _a           =    ids_tensor((self.batch_size, 3)					,  vocab_size=2			)

      # append to next input_ids and
      _a           =    torch.cat([input_ids, next_tokens]					,  dim=-1			)
      _a           =    torch.cat([input_mask, next_mask]					,  dim=-1			)

      _a           =    model(
          A					,  attention_mask=A					,  encoder_hidden_states=A					,  encoder_attention_mask=A					,  output_hidden_states=A					,  )['''hidden_states'''][0]
      _a           =    model(
          A					,  attention_mask=A					,  encoder_hidden_states=A					,  encoder_attention_mask=A					,  past_key_values=A					,  output_hidden_states=A					,  )['''hidden_states'''][0]

      # select random slice
      _a           =    ids_tensor((1,)					,  output_from_past.shape[-1]			).item()
      _a           =    output_from_no_past[:, -3:, random_slice_idx].detach()
      _a           =    output_from_past[:, :, random_slice_idx].detach()

      self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]			)

      # test that outputs are equal for slice
      self.parent.assertTrue(torch.allclose(A					,  A					,  atol=1E-3			)			)



 def    a__    (self			)       ->	Optional[Any]:


      """simple docstring"""



      _a           =    self.prepare_config_and_inputs()
      (
          (
          _a
      )    ,       (
          _a
      )    ,       (
          _a
      )    ,       (
          _a
      )    ,       (
          _a
      )    ,       (
          _a
      )    ,       (
          _a
      )    ,       
      )           =    config_and_inputs
      _a           =    {'''input_ids''': input_ids, '''attention_mask''': input_mask}
      return config, inputs_dict






@require_torch
class __A     (    A  ,  A  ,  A  ,  unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase       :			Optional[int]		=			(
     (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
 )
 __lowerCamelCase       :			Any		=			(OpenLlamaForCausalLM,) if is_torch_available() else ()
 __lowerCamelCase       :			List[Any]		=			(
     {
         'feature-extraction': OpenLlamaModel,
         'text-classification': OpenLlamaForSequenceClassification,
         'text-generation': OpenLlamaForCausalLM,
         'zero-shot': OpenLlamaForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __lowerCamelCase       :			List[str]		=			False
 __lowerCamelCase       :			List[str]		=			False



 def    a__    (self			)       ->	Tuple:


      """simple docstring"""



      _a           =    OpenLlamaModelTester(self			)
      _a           =    ConfigTester(self					,  config_class=A					,  hidden_size=37			)



 def    a__    (self			)       ->	List[str]:


      """simple docstring"""



      self.config_tester.run_common_tests()



 def    a__    (self			)       ->	Union[str, Any]:


      """simple docstring"""



      _a           =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A			)



 def    a__    (self			)       ->	str:


      """simple docstring"""



      _a           =    self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
           _a           =    type
           self.model_tester.create_and_check_model(*A			)



 def    a__    (self			)       ->	Any:


      """simple docstring"""



      _a    ,       _a           =    self.model_tester.prepare_config_and_inputs_for_common()
      _a           =    3
      _a           =    input_dict['''input_ids''']
      _a           =    input_ids.ne(1			).to(A			)
      _a           =    ids_tensor([self.model_tester.batch_size]					,  self.model_tester.type_sequence_label_size			)
      _a           =    OpenLlamaForSequenceClassification(A			)
      model.to(A			)
      model.eval()
      _a           =    model(A					,  attention_mask=A					,  labels=A			)
      self.assertEqual(result.logits.shape					,  (self.model_tester.batch_size, self.model_tester.num_labels)			)



 def    a__    (self			)       ->	Dict:


      """simple docstring"""



      _a    ,       _a           =    self.model_tester.prepare_config_and_inputs_for_common()
      _a           =    3
      _a           =    '''single_label_classification'''
      _a           =    input_dict['''input_ids''']
      _a           =    input_ids.ne(1			).to(A			)
      _a           =    ids_tensor([self.model_tester.batch_size]					,  self.model_tester.type_sequence_label_size			)
      _a           =    OpenLlamaForSequenceClassification(A			)
      model.to(A			)
      model.eval()
      _a           =    model(A					,  attention_mask=A					,  labels=A			)
      self.assertEqual(result.logits.shape					,  (self.model_tester.batch_size, self.model_tester.num_labels)			)



 def    a__    (self			)       ->	Optional[Any]:


      """simple docstring"""



      _a    ,       _a           =    self.model_tester.prepare_config_and_inputs_for_common()
      _a           =    3
      _a           =    '''multi_label_classification'''
      _a           =    input_dict['''input_ids''']
      _a           =    input_ids.ne(1			).to(A			)
      _a           =    ids_tensor(
          [self.model_tester.batch_size, config.num_labels]					,  self.model_tester.type_sequence_label_size			).to(torch.float			)
      _a           =    OpenLlamaForSequenceClassification(A			)
      model.to(A			)
      model.eval()
      _a           =    model(A					,  attention_mask=A					,  labels=A			)
      self.assertEqual(result.logits.shape					,  (self.model_tester.batch_size, self.model_tester.num_labels)			)



 @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test'''			)
 def    a__    (self			)       ->	Optional[Any]:


      """simple docstring"""



      pass



 @parameterized.expand([('''linear''',), ('''dynamic''',)]			)
 def    a__    (self					,  A			)       ->	Optional[int]:


      """simple docstring"""



      _a    ,       _a           =    self.model_tester.prepare_config_and_inputs_for_common()
      _a           =    ids_tensor([1, 10]					,  config.vocab_size			)
      _a           =    ids_tensor([1, int(config.max_position_embeddings * 1.5			)]					,  config.vocab_size			)

      set_seed(42			)  # Fixed seed at init time so the two models get the same random weights
      _a           =    OpenLlamaModel(A			)
      original_model.to(A			)
      original_model.eval()
      _a           =    original_model(A			).last_hidden_state
      _a           =    original_model(A			).last_hidden_state

      set_seed(42			)  # Fixed seed at init time so the two models get the same random weights
      _a           =    {'''type''': scaling_type, '''factor''': 10.0}
      _a           =    OpenLlamaModel(A			)
      scaled_model.to(A			)
      scaled_model.eval()
      _a           =    scaled_model(A			).last_hidden_state
      _a           =    scaled_model(A			).last_hidden_state

      # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
      # maximum sequence length, so the outputs for the short input should match.
      if scaling_type == "dynamic":
           self.assertTrue(torch.allclose(A					,  A					,  atol=1E-5			)			)
      else:
           self.assertFalse(torch.allclose(A					,  A					,  atol=1E-5			)			)

      # The output should be different for long inputs
      self.assertFalse(torch.allclose(A					,  A					,  atol=1E-5			)			)



