






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       :






  """simple docstring"""





  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=7		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=True		,		_UpperCAmelCase=99		,		_UpperCAmelCase=32		,		_UpperCAmelCase=2		,		_UpperCAmelCase=4		,		_UpperCAmelCase=37		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=512		,		_UpperCAmelCase=16		,		_UpperCAmelCase=2		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=3		,		_UpperCAmelCase=4		,		_UpperCAmelCase=None		,		_UpperCAmelCase=0		,		)			-> Any:
     UpperCamelCase_									=     parent
     UpperCamelCase_									=     batch_size
     UpperCamelCase_									=     seq_length
     UpperCamelCase_									=     is_training
     UpperCamelCase_									=     use_input_mask
     UpperCamelCase_									=     use_token_type_ids
     UpperCamelCase_									=     use_labels
     UpperCamelCase_									=     vocab_size
     UpperCamelCase_									=     hidden_size
     UpperCamelCase_									=     num_hidden_layers
     UpperCamelCase_									=     num_attention_heads
     UpperCamelCase_									=     intermediate_size
     UpperCamelCase_									=     hidden_act
     UpperCamelCase_									=     hidden_dropout_prob
     UpperCamelCase_									=     attention_probs_dropout_prob
     UpperCamelCase_									=     max_position_embeddings
     UpperCamelCase_									=     type_vocab_size
     UpperCamelCase_									=     type_sequence_label_size
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     num_labels
     UpperCamelCase_									=     num_choices
     UpperCamelCase_									=     scope
     UpperCamelCase_									=     projection_dim




  def    _UpperCAmelCase     (     self )			-> int:
     UpperCamelCase_									=     ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size )

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

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

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

     UpperCamelCase_									=     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=_UpperCAmelCase		,		initializer_range=self.initializer_range		,		)
     UpperCamelCase_									=     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    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_									=     TFDPRContextEncoder(config=_UpperCAmelCase )
     UpperCamelCase_									=     model(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase		,		token_type_ids=_UpperCAmelCase )
     UpperCamelCase_									=     model(_UpperCAmelCase		,		token_type_ids=_UpperCAmelCase )
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.pooler_output.shape		,		(self.batch_size, self.projection_dim or self.hidden_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Tuple:
     UpperCamelCase_									=     TFDPRQuestionEncoder(config=_UpperCAmelCase )
     UpperCamelCase_									=     model(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase		,		token_type_ids=_UpperCAmelCase )
     UpperCamelCase_									=     model(_UpperCAmelCase		,		token_type_ids=_UpperCAmelCase )
     UpperCamelCase_									=     model(_UpperCAmelCase )
     self.parent.assertEqual(result.pooler_output.shape		,		(self.batch_size, self.projection_dim or self.hidden_size) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Union[str, Any]:
     UpperCamelCase_									=     TFDPRReader(config=_UpperCAmelCase )
     UpperCamelCase_									=     model(_UpperCAmelCase		,		attention_mask=_UpperCAmelCase )

     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    _UpperCAmelCase     (     self )			-> int:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     (
         (
         UpperCamelCase_      
     )		,      (
         UpperCamelCase_      
     )		,      (
         UpperCamelCase_      
     )		,      (
         UpperCamelCase_      
     )		,      (
         UpperCamelCase_      
     )		,      (
         UpperCamelCase_      
     )		,      (
         UpperCamelCase_      
     )		,            
     )									=     config_and_inputs
     UpperCamelCase_									=     {'input_ids': input_ids}
     return config, inputs_dict



@require_tf
class 						_a       (  UpperCAmelCase__						,       UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  A_						=   (
      (
          TFDPRContextEncoder,
          TFDPRQuestionEncoder,
          TFDPRReader,
      )
      if is_tf_available()
      else ()
  )
  A_						=   {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

  A_						=   False
  A_						=   False
  A_						=   False
  A_						=   False
  A_						=   False




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     TFDPRModelTester(self )
     UpperCamelCase_									=     ConfigTester(self		,		config_class=_UpperCAmelCase		,		hidden_size=37 )




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     self.config_tester.run_common_tests()




  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_context_encoder(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_question_encoder(*_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> int:
     UpperCamelCase_									=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_reader(*_UpperCAmelCase )




  @slow
  def    _UpperCAmelCase     (     self )			-> Dict:
     for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase_									=     TFDPRContextEncoder.from_pretrained(_UpperCAmelCase )
        self.assertIsNotNone(_UpperCAmelCase )

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

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

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



@require_tf
class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  @slow
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base' )

     UpperCamelCase_									=     tf.constant(
         [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]] )  # [CLS] hello, is my dog cute? [SEP]
     UpperCamelCase_									=     model(_UpperCAmelCase )[0]  # embedding shape = (1, 768)
     # compare the actual values for a slice.
     UpperCamelCase_									=     tf.constant(
         [
             [
                 0.0_3_2_3_6_2_5_3,
                 0.1_2_7_5_3_3_3_5,
                 0.1_6_8_1_8_5_0_9,
                 0.0_0_2_7_9_7_8_6,
                 0.3_8_9_6_9_3_3,
                 0.2_4_2_6_4_9_4_5,
                 0.2_1_7_8_9_7_1,
                 -0.0_2_3_3_5_2_2_7,
                 -0.0_8_4_8_1_9_5_9,
                 -0.1_4_3_2_4_1_1_7,
             ]
         ] )
     self.assertTrue(numpy.allclose(output[:, :10].numpy()		,		expected_slice.numpy()		,		atol=1e-4 ) )













import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


snake_case__      :	str       	=      logging.getLogger(__name__)


@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None




@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None
  A_						=   None


if is_torch_available():
 import torch
 from torch.utils.data import Dataset


 class 						_a       (  UpperCAmelCase__    ):






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> Any:
      UpperCamelCase_									=     hans_processors[task]()

      UpperCamelCase_									=     os.path.join(
          _UpperCAmelCase		,		'cached_{}_{}_{}_{}'.format(
              'dev' if evaluate else 'train'		,		tokenizer.__class__.__name__		,		str(_UpperCAmelCase )		,		_UpperCAmelCase		,		)		,		)
      UpperCamelCase_									=     processor.get_labels()
      if tokenizer.__class__ in (
          RobertaTokenizer,
          RobertaTokenizerFast,
          XLMRobertaTokenizer,
          BartTokenizer,
          BartTokenizerFast,
      ):
         # HACK(label indices are swapped in RoBERTa pretrained model)
         UpperCamelCase_		,      UpperCamelCase_									=     label_list[2], label_list[1]
      UpperCamelCase_									=     label_list

      # Make sure only the first process in distributed training processes the dataset,
      # and the others will use the cache.
      UpperCamelCase_									=     cached_features_file + '.lock'
      with FileLock(_UpperCAmelCase ):
         if os.path.exists(_UpperCAmelCase ) and not overwrite_cache:
            logger.info(f"""Loading features from cached file {cached_features_file}""" )
            UpperCamelCase_									=     torch.load(_UpperCAmelCase )
         else:
            logger.info(f"""Creating features from dataset file at {data_dir}""" )

            UpperCamelCase_									=     (
                processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
            )

            logger.info('Training examples: %s'		,		len(_UpperCAmelCase ) )
            UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
            logger.info('Saving features into cached file %s'		,		_UpperCAmelCase )
            torch.save(self.features		,		_UpperCAmelCase )




   def __len__(     self )			-> Dict:
      return len(self.features )




   def __getitem__(     self		,		_UpperCAmelCase )			-> InputFeatures:
      return self.features[i]




   def    _UpperCAmelCase     (     self )			-> Dict:
      return self.label_list


if is_tf_available():
 import tensorflow as tf


 class 						_a       :






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = 128		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> int:
      UpperCamelCase_									=     hans_processors[task]()
      UpperCamelCase_									=     processor.get_labels()
      if tokenizer.__class__ in (
          RobertaTokenizer,
          RobertaTokenizerFast,
          XLMRobertaTokenizer,
          BartTokenizer,
          BartTokenizerFast,
      ):
         # HACK(label indices are swapped in RoBERTa pretrained model)
         UpperCamelCase_		,      UpperCamelCase_									=     label_list[2], label_list[1]
      UpperCamelCase_									=     label_list

      UpperCamelCase_									=     processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
      UpperCamelCase_									=     hans_convert_examples_to_features(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )

      def gen():
         for ex_index, ex in tqdm.tqdm(enumerate(self.features )		,		desc='convert examples to features' ):
            if ex_index % 10000 == 0:
               logger.info('Writing example %d of %d' % (ex_index, len(_UpperCAmelCase )) )

            yield (
                {
                    "example_id": 0,
                    "input_ids": ex.input_ids,
                    "attention_mask": ex.attention_mask,
                    "token_type_ids": ex.token_type_ids,
                },
                ex.label,
            )

      UpperCamelCase_									=     tf.data.Dataset.from_generator(
          _UpperCAmelCase		,		(
              {
                  'example_id': tf.intaa,
                  'input_ids': tf.intaa,
                  'attention_mask': tf.intaa,
                  'token_type_ids': tf.intaa,
              },
              tf.intaa,
          )		,		(
              {
                  'example_id': tf.TensorShape([] ),
                  'input_ids': tf.TensorShape([None, None] ),
                  'attention_mask': tf.TensorShape([None, None] ),
                  'token_type_ids': tf.TensorShape([None, None] ),
              },
              tf.TensorShape([] ),
          )		,		)




   def    _UpperCAmelCase     (     self )			-> List[str]:
      return self.dataset




   def __len__(     self )			-> str:
      return len(self.features )




   def __getitem__(     self		,		_UpperCAmelCase )			-> InputFeatures:
      return self.features[i]




   def    _UpperCAmelCase     (     self )			-> int:
      return self.label_list


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Tuple:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_train_set.txt' ) )		,		'train' )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Dict:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_evaluation_set.txt' ) )		,		'dev' )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     return ["contradiction", "entailment", "neutral"]




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     UpperCamelCase_									=     []
     for i, line in enumerate(_UpperCAmelCase ):
        if i == 0:
           continue
        UpperCamelCase_									=     '%s-%s' % (set_type, line[0])
        UpperCamelCase_									=     line[5]
        UpperCamelCase_									=     line[6]
        UpperCamelCase_									=     line[7][2:] if line[7].startswith('ex' ) else line[7]
        UpperCamelCase_									=     line[0]
        examples.append(InputExample(guid=_UpperCAmelCase		,		text_a=_UpperCAmelCase		,		text_b=_UpperCAmelCase		,		label=_UpperCAmelCase		,		pairID=_UpperCAmelCase ) )
     return examples






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase    ,      ):
   UpperCamelCase_									=     {label: i for i, label in enumerate(__lowercase)}

   UpperCamelCase_									=     []
   for ex_index, example in tqdm.tqdm(enumerate(__lowercase)    ,      desc='convert examples to features'):
      if ex_index % 10000 == 0:
         logger.info('Writing example %d' % (ex_index))

      UpperCamelCase_									=     tokenizer(
          example.text_a    ,      example.text_b    ,      add_special_tokens=__lowercase    ,      max_length=__lowercase    ,      padding='max_length'    ,      truncation=__lowercase    ,      return_overflowing_tokens=__lowercase    ,      )

      UpperCamelCase_									=     label_map[example.label] if example.label in label_map else 0

      UpperCamelCase_									=     int(example.pairID)

      features.append(InputFeatures(**__lowercase    ,      label=__lowercase    ,      pairID=__lowercase))

   for i, example in enumerate(examples[:5]):
      logger.info('*** Example ***')
      logger.info(f"""guid: {example}""")
      logger.info(f"""features: {features[i]}""")

   return features


snake_case__      :	List[str]       	=      {
    """hans""": 3,
}

snake_case__      :	Union[str, Any]       	=      {
    """hans""": HansProcessor,
}





