






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        __UpperCamelCase    :







	def __init__(  self      :							Optional[int]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Any=13       ,				_lowerCAmelCase      :							int=7       ,				_lowerCAmelCase      :							Any=True       ,				_lowerCAmelCase      :							Optional[Any]=True       ,				_lowerCAmelCase      :							Any=True       ,				_lowerCAmelCase      :							Any=True       ,				_lowerCAmelCase      :							Tuple=99       ,				_lowerCAmelCase      :							Optional[int]=32       ,				_lowerCAmelCase      :							Any=2       ,				_lowerCAmelCase      :							str=4       ,				_lowerCAmelCase      :							Optional[Any]=37       ,				_lowerCAmelCase      :							int="gelu"       ,				_lowerCAmelCase      :							List[str]=0.1       ,				_lowerCAmelCase      :							List[Any]=0.1       ,				_lowerCAmelCase      :							str=512       ,				_lowerCAmelCase      :							str=16       ,				_lowerCAmelCase      :							Any=2       ,				_lowerCAmelCase      :							int=0.02       ,				_lowerCAmelCase      :							Union[str, Any]=3       ,				_lowerCAmelCase      :							Tuple=4       ,				_lowerCAmelCase      :							str=None       ,				_lowerCAmelCase      :							str=0       ,				)		-> List[Any]:
		"""simple docstring"""







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







	def  _a   (  self      :							Any			)		-> List[Any]:
		"""simple docstring"""







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

		__lowercase			       =  None
		if self.use_input_mask:
			# follow test_modeling_tf_ctrl.py
			__lowercase			       =  random_attention_mask([self.batch_size, self.seq_length]			)

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

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

		__lowercase			       =  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=__A       ,				initializer_range=self.initializer_range       ,				)
		__lowercase			       =  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  _a   (  self      :							List[str]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Union[str, Any]			)		-> List[Any]:
		"""simple docstring"""







		__lowercase			       =  TFDPRContextEncoder(config=__A			)
		__lowercase			       =  model(__A       ,				attention_mask=__A       ,				token_type_ids=__A			)
		__lowercase			       =  model(__A       ,				token_type_ids=__A			)
		__lowercase			       =  model(__A			)
		self.parent.assertEqual(result.pooler_output.shape       ,				(self.batch_size, self.projection_dim or self.hidden_size)			)







	def  _a   (  self      :							Dict       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Tuple			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase			       =  TFDPRQuestionEncoder(config=__A			)
		__lowercase			       =  model(__A       ,				attention_mask=__A       ,				token_type_ids=__A			)
		__lowercase			       =  model(__A       ,				token_type_ids=__A			)
		__lowercase			       =  model(__A			)
		self.parent.assertEqual(result.pooler_output.shape       ,				(self.batch_size, self.projection_dim or self.hidden_size)			)







	def  _a   (  self      :							int       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Any			)		-> Tuple:
		"""simple docstring"""







		__lowercase			       =  TFDPRReader(config=__A			)
		__lowercase			       =  model(__A       ,				attention_mask=__A			)

		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  _a   (  self      :							List[Any]			)		-> int:
		"""simple docstring"""







		__lowercase			       =  self.prepare_config_and_inputs()
		(
		    __lowercase		
		)			       =  config_and_inputs
		__lowercase			       =  {"input_ids": input_ids}
		return config, inputs_dict


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:int   =       (
	    (
	        TFDPRContextEncoder,
	        TFDPRQuestionEncoder,
	        TFDPRReader,
	    )
	    if is_tf_available()
	    else ()
	)
	__snake_case	:List[str]   =       {'feature-extraction': TFDPRQuestionEncoder} if is_tf_available() else {}

	__snake_case	:str   =       False
	__snake_case	:int   =       False
	__snake_case	:Dict   =       False
	__snake_case	:Optional[Any]   =       False
	__snake_case	:str   =       False







	def  _a   (  self      :							Union[str, Any]			)		-> Any:
		"""simple docstring"""







		__lowercase			       =  TFDPRModelTester(self			)
		__lowercase			       =  ConfigTester(self       ,				config_class=__A       ,				hidden_size=37			)







	def  _a   (  self      :							str			)		-> Union[str, Any]:
		"""simple docstring"""







		self.config_tester.run_common_tests()







	def  _a   (  self      :							List[str]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase			       =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_dpr_context_encoder(*__A			)







	def  _a   (  self      :							Dict			)		-> Any:
		"""simple docstring"""







		__lowercase			       =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_dpr_question_encoder(*__A			)







	def  _a   (  self      :							List[Any]			)		-> Tuple:
		"""simple docstring"""







		__lowercase			       =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_dpr_reader(*__A			)







	@slow
	def  _a   (  self      :							Any			)		-> Dict:
		"""simple docstring"""







		for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			__lowercase			       =  TFDPRContextEncoder.from_pretrained(__A			)
			self.assertIsNotNone(__A			)

		for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			__lowercase			       =  TFDPRContextEncoder.from_pretrained(__A			)
			self.assertIsNotNone(__A			)

		for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			__lowercase			       =  TFDPRQuestionEncoder.from_pretrained(__A			)
			self.assertIsNotNone(__A			)

		for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			__lowercase			       =  TFDPRReader.from_pretrained(__A			)
			self.assertIsNotNone(__A			)


@require_tf
class        __UpperCamelCase    (     unittest.TestCase   ):







	@slow
	def  _a   (  self      :							Any			)		-> int:
		"""simple docstring"""







		__lowercase			       =  TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""			)

		__lowercase			       =  tf.constant(
		    [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]			)  # [CLS] hello, is my dog cute? [SEP]
		__lowercase			       =  model(__A			)[0]  # embedding shape = (1, 768)
		# compare the actual values for a slice.
		__lowercase			       =  tf.constant(
		    [
		        [
		            0.03_236_253,
		            0.12_753_335,
		            0.16_818_509,
		            0.00_279_786,
		            0.3_896_933,
		            0.24_264_945,
		            0.2_178_971,
		            -0.02_335_227,
		            -0.08_481_959,
		            -0.14_324_117,
		        ]
		    ]			)
		self.assertTrue(numpy.allclose(output[:, :10].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


__UpperCamelCase      :      Any     						=						logging.get_logger(__name__)


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







	def  _a   (  self      :							Dict			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.task_name.lower()


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Optional[int]   =       'train'
	__snake_case	:int   =       'dev'
	__snake_case	:Any   =       'test'


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:GlueDataTrainingArguments
	__snake_case	:str
	__snake_case	:List[InputFeatures]







	def __init__(  self      :							Dict       ,				_lowerCAmelCase      :							GlueDataTrainingArguments       ,				_lowerCAmelCase      :							PreTrainedTokenizerBase       ,				_lowerCAmelCase      :							Optional[int] = None       ,				_lowerCAmelCase      :							Union[str, Split] = Split.train       ,				_lowerCAmelCase      :							Optional[str] = None       ,				)		-> List[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"""       ,				_lowerCAmelCase       ,				)
		__lowercase             =  args
		__lowercase             =  glue_processors[args.task_name]()
		__lowercase             =  glue_output_modes[args.task_name]
		if isinstance(_lowerCAmelCase       ,				_lowerCAmelCase			):
			try:
				__lowercase             =  Split[mode]
			except KeyError:
				raise KeyError("""mode is not a valid split name"""			)
        # Load data features from cache or dataset file
		__lowercase             =  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}'       ,				)
		__lowercase             =  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)
			__lowercase       ,						__lowercase             =  label_list[2], label_list[1]
		__lowercase             =  label_list

		# Make sure only the first process in distributed training processes the dataset,
		# and the others will use the cache.
		__lowercase             =  cached_features_file + """.lock"""
		with FileLock(_lowerCAmelCase			):
			if os.path.exists(_lowerCAmelCase			) and not args.overwrite_cache:
				__lowercase             =  time.time()
				__lowercase             =  torch.load(_lowerCAmelCase			)
				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:
					__lowercase             =  self.processor.get_dev_examples(args.data_dir			)
				elif mode == Split.test:
					__lowercase             =  self.processor.get_test_examples(args.data_dir			)
				else:
					__lowercase             =  self.processor.get_train_examples(args.data_dir			)
				if limit_length is not None:
					__lowercase             =  examples[:limit_length]
				__lowercase             =  glue_convert_examples_to_features(
				    _lowerCAmelCase       ,				_lowerCAmelCase       ,				max_length=args.max_seq_length       ,				label_list=_lowerCAmelCase       ,				output_mode=self.output_mode       ,				)
				__lowercase             =  time.time()
				torch.save(self.features       ,				_lowerCAmelCase			)
				# ^ 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      :							Dict			)		-> Optional[int]:
		"""simple docstring"""







		return len(self.features			)







	def __getitem__(  self      :							Tuple       ,				_lowerCAmelCase      :							Optional[int]			)		-> InputFeatures:
		"""simple docstring"""







		return self.features[i]







	def  _a   (  self      :							str			)		-> int:
		"""simple docstring"""







		return self.label_list

