





from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import numpy
       import tensorflow as tf

       from transformers import (
           TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
           TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
           TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
           BertConfig,
           DPRConfig,
           TFDPRContextEncoder,
           TFDPRQuestionEncoder,
           TFDPRReader,
       )






class        _a:







  def __init__(    self ,						__snake_case ,						__snake_case=1_3 ,						__snake_case=7 ,						__snake_case=True ,						__snake_case=True ,						__snake_case=True ,						__snake_case=True ,						__snake_case=9_9 ,						__snake_case=3_2 ,						__snake_case=2 ,						__snake_case=4 ,						__snake_case=3_7 ,						__snake_case="gelu" ,						__snake_case=0.1 ,						__snake_case=0.1 ,						__snake_case=5_1_2 ,						__snake_case=1_6 ,						__snake_case=2 ,						__snake_case=0.02 ,						__snake_case=3 ,						__snake_case=4 ,						__snake_case=None ,						__snake_case=0 ,						)      ->      int:


       '''simple docstring'''

       _snake_case       :					Optional[int]				       =   parent
       _snake_case       :					Dict				       =   batch_size
       _snake_case       :					Optional[Any]				       =   seq_length
       _snake_case       :					Union[str, Any]				       =   is_training
       _snake_case       :					Optional[Any]				       =   use_input_mask
       _snake_case       :					List[str]				       =   use_token_type_ids
       _snake_case       :					Tuple				       =   use_labels
       _snake_case       :					int				       =   vocab_size
       _snake_case       :					List[Any]				       =   hidden_size
       _snake_case       :					Tuple				       =   num_hidden_layers
       _snake_case       :					Any				       =   num_attention_heads
       _snake_case       :					int				       =   intermediate_size
       _snake_case       :					int				       =   hidden_act
       _snake_case       :					Optional[int]				       =   hidden_dropout_prob
       _snake_case       :					Optional[int]				       =   attention_probs_dropout_prob
       _snake_case       :					List[Any]				       =   max_position_embeddings
       _snake_case       :					Tuple				       =   type_vocab_size
       _snake_case       :					List[Any]				       =   type_sequence_label_size
       _snake_case       :					List[str]				       =   initializer_range
       _snake_case       :					Optional[Any]				       =   num_labels
       _snake_case       :					Any				       =   num_choices
       _snake_case       :					Optional[int]				       =   scope
       _snake_case       :					Any				       =   projection_dim







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


       '''simple docstring'''

       _snake_case       :					str				       =   ids_tensor([self.batch_size, self.seq_length] ,						self.vocab_size				)

       _snake_case       :					Optional[Any]				       =   None
       if self.use_input_mask:
            # follow test_modeling_tf_ctrl.py
            _snake_case       :					Union[str, Any]				       =   random_attention_mask([self.batch_size, self.seq_length]				)

       _snake_case       :					Dict				       =   None
       if self.use_token_type_ids:
            _snake_case       :					Optional[int]				       =   ids_tensor([self.batch_size, self.seq_length] ,						self.type_vocab_size				)

       _snake_case       :					Union[str, Any]				       =   None
       _snake_case       :					Tuple				       =   None
       _snake_case       :					Any				       =   None
       if self.use_labels:
            _snake_case       :					Dict				       =   ids_tensor([self.batch_size] ,						self.type_sequence_label_size				)
            _snake_case       :					Any				       =   ids_tensor([self.batch_size, self.seq_length] ,						self.num_labels				)
            _snake_case       :					Dict				       =   ids_tensor([self.batch_size] ,						self.num_choices				)

       _snake_case       :					List[Any]				       =   BertConfig(
           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=__snake_case ,						initializer_range=self.initializer_range ,						)
       _snake_case       :					int				       =   DPRConfig(projection_dim=self.projection_dim ,						**config.to_dict()				)

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







  def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      List[Any]:


       '''simple docstring'''

       _snake_case       :					str				       =   TFDPRContextEncoder(config=__snake_case				)
       _snake_case       :					str				       =   model(__snake_case ,						attention_mask=__snake_case ,						token_type_ids=__snake_case				)
       _snake_case       :					Union[str, Any]				       =   model(__snake_case ,						token_type_ids=__snake_case				)
       _snake_case       :					Optional[int]				       =   model(__snake_case				)
       self.parent.assertEqual(result.pooler_output.shape ,						(self.batch_size, self.projection_dim or self.hidden_size)				)







  def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      Any:


       '''simple docstring'''

       _snake_case       :					int				       =   TFDPRQuestionEncoder(config=__snake_case				)
       _snake_case       :					List[Any]				       =   model(__snake_case ,						attention_mask=__snake_case ,						token_type_ids=__snake_case				)
       _snake_case       :					str				       =   model(__snake_case ,						token_type_ids=__snake_case				)
       _snake_case       :					Tuple				       =   model(__snake_case				)
       self.parent.assertEqual(result.pooler_output.shape ,						(self.batch_size, self.projection_dim or self.hidden_size)				)







  def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      Dict:


       '''simple docstring'''

       _snake_case       :					List[str]				       =   TFDPRReader(config=__snake_case				)
       _snake_case       :					Tuple				       =   model(__snake_case ,						attention_mask=__snake_case				)

       self.parent.assertEqual(result.start_logits.shape ,						(self.batch_size, self.seq_length)				)
       self.parent.assertEqual(result.end_logits.shape ,						(self.batch_size, self.seq_length)				)
       self.parent.assertEqual(result.relevance_logits.shape ,						(self.batch_size,)				)







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


       '''simple docstring'''

       _snake_case       :					str				       =   self.prepare_config_and_inputs()
       (
           _snake_case	
       )       :					Tuple				       =   config_and_inputs
       _snake_case       :					Optional[Any]				       =   {'''input_ids''': input_ids}
       return config, inputs_dict






@require_tf
class        _a(    UpperCamelCase_	,   UpperCamelCase_	,   unittest.TestCase    ):
  lowerCamelCase__     :Dict   				=		(
      (
          TFDPRContextEncoder,
          TFDPRQuestionEncoder,
          TFDPRReader,
      )
      if is_tf_available()
      else ()
  )
  lowerCamelCase__     :Tuple   				=		{'feature-extraction': TFDPRQuestionEncoder} if is_tf_available() else {}

  lowerCamelCase__     :List[Any]   				=		False
  lowerCamelCase__     :Optional[int]   				=		False
  lowerCamelCase__     :int   				=		False
  lowerCamelCase__     :Dict   				=		False
  lowerCamelCase__     :Union[str, Any]   				=		False







  def        lowercase       (    self				)      ->      Tuple:


       '''simple docstring'''

       _snake_case       :					Tuple				       =   TFDPRModelTester(self				)
       _snake_case       :					List[str]				       =   ConfigTester(self ,						config_class=__snake_case ,						hidden_size=3_7				)







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


       '''simple docstring'''

       self.config_tester.run_common_tests()







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


       '''simple docstring'''

       _snake_case       :					str				       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_dpr_context_encoder(*__snake_case				)







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


       '''simple docstring'''

       _snake_case       :					int				       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_dpr_question_encoder(*__snake_case				)







  def        lowercase       (    self				)      ->      Any:


       '''simple docstring'''

       _snake_case       :					Optional[Any]				       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_dpr_reader(*__snake_case				)







  @slow
  def        lowercase       (    self				)      ->      str:


       '''simple docstring'''

       for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _snake_case       :					List[str]				       =   TFDPRContextEncoder.from_pretrained(__snake_case				)
            self.assertIsNotNone(__snake_case				)

       for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _snake_case       :					Dict				       =   TFDPRContextEncoder.from_pretrained(__snake_case				)
            self.assertIsNotNone(__snake_case				)

       for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _snake_case       :					List[str]				       =   TFDPRQuestionEncoder.from_pretrained(__snake_case				)
            self.assertIsNotNone(__snake_case				)

       for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _snake_case       :					Union[str, Any]				       =   TFDPRReader.from_pretrained(__snake_case				)
            self.assertIsNotNone(__snake_case				)






@require_tf
class        _a(    unittest.TestCase    ):







  @slow
  def        lowercase       (    self				)      ->      Optional[int]:


       '''simple docstring'''

       _snake_case       :					List[Any]				       =   TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base"				)

       _snake_case       :					List[Any]				       =   tf.constant(
           [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]]				)  # [CLS] hello, is my dog cute? [SEP]
       _snake_case       :					Tuple				       =   model(__snake_case				)[0]  # embedding shape = (1, 768)
       # compare the actual values for a slice.
       _snake_case       :					Any				       =   tf.constant(
           [
               [
                   0.03_23_62_53,
                   0.12_75_33_35,
                   0.16_81_85_09,
                   0.00_27_97_86,
                   0.3_89_69_33,
                   0.24_26_49_45,
                   0.2_17_89_71,
                   -0.02_33_52_27,
                   -0.08_48_19_59,
                   -0.14_32_41_17,
               ]
           ]				)
       self.assertTrue(numpy.allclose(output[:, :1_0].numpy() ,						expected_slice.numpy() ,						atol=1E-4				)				)






import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


__lowerCAmelCase :Tuple     =    logging.get_logger(__name__)






@dataclass
class        _a:
		lowerCamelCase__     :str   				=		field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys()    )}    )
		lowerCamelCase__     :str   				=		field(
		    metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the 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__     :bool   				=		field(
		    default=__A	,   metadata={'help': 'Overwrite the cached training and evaluation sets'}    )







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


							'''simple docstring'''

							_snake_case       :					Dict				       =   self.task_name.lower()






class        _a(    __A    ):
		lowerCamelCase__     :Optional[Any]   				=		'train'
		lowerCamelCase__     :List[str]   				=		'dev'
		lowerCamelCase__     :Any   				=		'test'






class        _a(    __A    ):
		lowerCamelCase__     :GlueDataTrainingArguments
		lowerCamelCase__     :str
		lowerCamelCase__     :List[InputFeatures]







		def __init__(    self ,						__snake_case ,						__snake_case ,						__snake_case = None ,						__snake_case = Split.train ,						__snake_case = None ,						)      ->      Any:


							'''simple docstring'''

							warnings.warn(
							    "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
							    "library. You can have a look at this example script for pointers: "
							    "https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py" ,						__snake_case ,						)
							_snake_case       :					Optional[Any]				       =   args
							_snake_case       :					Optional[int]				       =   glue_processors[args.task_name]()
							_snake_case       :					int				       =   glue_output_modes[args.task_name]
							if isinstance(__snake_case ,						__snake_case				):
												try:
																	_snake_case       :					Tuple				       =   Split[mode]
												except KeyError:
																	raise KeyError("mode is not a valid split name"				)
        # Load data features from cache or dataset file
							_snake_case       :					List[str]				       =   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}_{args.task_name}""" ,						)
							_snake_case       :					List[Any]				       =   self.processor.get_labels()
							if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
							    "RobertaTokenizer",
							    "RobertaTokenizerFast",
							    "XLMRobertaTokenizer",
							    "BartTokenizer",
							    "BartTokenizerFast",
							):
												# HACK(label indices are swapped in RoBERTa pretrained model)
												_snake_case       , _snake_case       :					int				       =   label_list[2], label_list[1]
							_snake_case       :					str				       =   label_list

							# Make sure only the first process in distributed training processes the dataset,
							# and the others will use the cache.
							_snake_case       :					Optional[Any]				       =   cached_features_file + ".lock"
							with FileLock(__snake_case				):
												if os.path.exists(__snake_case				) and not args.overwrite_cache:
																	_snake_case       :					List[str]				       =   time.time()
																	_snake_case       :					str				       =   torch.load(__snake_case				)
																	logger.info(
																	    f"""Loading features from cached file {cached_features_file} [took %.3f s]""" ,						time.time() - start				)
												else:
																	logger.info(f"""Creating features from dataset file at {args.data_dir}"""				)

																	if mode == Split.dev:
																						_snake_case       :					List[Any]				       =   self.processor.get_dev_examples(args.data_dir				)
																	elif mode == Split.test:
																						_snake_case       :					List[Any]				       =   self.processor.get_test_examples(args.data_dir				)
																	else:
																						_snake_case       :					str				       =   self.processor.get_train_examples(args.data_dir				)
																	if limit_length is not None:
																						_snake_case       :					Tuple				       =   examples[:limit_length]
																	_snake_case       :					List[str]				       =   glue_convert_examples_to_features(
																	    __snake_case ,						__snake_case ,						max_length=args.max_seq_length ,						label_list=__snake_case ,						output_mode=self.output_mode ,						)
																	_snake_case       :					Optional[Any]				       =   time.time()
																	torch.save(self.features ,						__snake_case				)
																	# ^ 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[str]:


							'''simple docstring'''

							return len(self.features				)







		def __getitem__(    self ,						__snake_case				)      ->      InputFeatures:


							'''simple docstring'''

							return self.features[i]







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


							'''simple docstring'''

							return self.label_list