






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 copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case__      :	Optional[int]       	=      logging.get_logger(__name__)

snake_case__      :	List[Any]       	=      {
    """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""",
}


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """git_vision_model"""




  def __init__(     self		,		_UpperCAmelCase=768		,		_UpperCAmelCase=3072		,		_UpperCAmelCase=12		,		_UpperCAmelCase=12		,		_UpperCAmelCase=3		,		_UpperCAmelCase=224		,		_UpperCAmelCase=16		,		_UpperCAmelCase="quick_gelu"		,		_UpperCAmelCase=1e-5		,		_UpperCAmelCase=0.0		,		_UpperCAmelCase=0.0_2		,		**_UpperCAmelCase		,		)			-> Optional[Any]:
     super().__init__(**_UpperCAmelCase )

     UpperCamelCase_									=     hidden_size
     UpperCamelCase_									=     intermediate_size
     UpperCamelCase_									=     num_hidden_layers
     UpperCamelCase_									=     num_attention_heads
     UpperCamelCase_									=     num_channels
     UpperCamelCase_									=     patch_size
     UpperCamelCase_									=     image_size
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     attention_dropout
     UpperCamelCase_									=     layer_norm_eps
     UpperCamelCase_									=     hidden_act




  @classmethod
  def    _UpperCAmelCase     (     cls		,		_UpperCAmelCase		,		**_UpperCAmelCase )			-> "PretrainedConfig":
     cls._set_token_in_kwargs(_UpperCAmelCase )

     UpperCamelCase_		,      UpperCamelCase_									=     cls.get_config_dict(_UpperCAmelCase		,		**_UpperCAmelCase )

     # get the vision config dict if we are loading from GITConfig
     if config_dict.get('model_type' ) == "git":
        UpperCamelCase_									=     config_dict['vision_config']

     if "model_type" in config_dict and hasattr(cls		,		'model_type' ) and config_dict["model_type"] != cls.model_type:
        logger.warning(
            f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
            f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" )

     return cls.from_dict(_UpperCAmelCase		,		**_UpperCAmelCase )




class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """git"""




  def __init__(     self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=30522		,		_UpperCAmelCase=768		,		_UpperCAmelCase=6		,		_UpperCAmelCase=12		,		_UpperCAmelCase=3072		,		_UpperCAmelCase="gelu"		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=1024		,		_UpperCAmelCase=0.0_2		,		_UpperCAmelCase=1e-12		,		_UpperCAmelCase=0		,		_UpperCAmelCase="absolute"		,		_UpperCAmelCase=True		,		_UpperCAmelCase=False		,		_UpperCAmelCase=101		,		_UpperCAmelCase=102		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)			-> Optional[int]:
     super().__init__(bos_token_id=_UpperCAmelCase		,		eos_token_id=_UpperCAmelCase		,		pad_token_id=_UpperCAmelCase		,		**_UpperCAmelCase )

     if vision_config is None:
        UpperCamelCase_									=     {}
        logger.info('vision_config is None. initializing the GitVisionConfig with default values.' )

     UpperCamelCase_									=     GitVisionConfig(**_UpperCAmelCase )
     UpperCamelCase_									=     vocab_size
     UpperCamelCase_									=     hidden_size
     UpperCamelCase_									=     num_hidden_layers
     UpperCamelCase_									=     num_attention_heads
     UpperCamelCase_									=     hidden_act
     UpperCamelCase_									=     intermediate_size
     UpperCamelCase_									=     hidden_dropout_prob
     UpperCamelCase_									=     attention_probs_dropout_prob
     UpperCamelCase_									=     max_position_embeddings
     UpperCamelCase_									=     initializer_range
     UpperCamelCase_									=     layer_norm_eps
     UpperCamelCase_									=     position_embedding_type
     UpperCamelCase_									=     use_cache
     UpperCamelCase_									=     tie_word_embeddings
     UpperCamelCase_									=     num_image_with_embedding

     UpperCamelCase_									=     bos_token_id
     UpperCamelCase_									=     eos_token_id




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     copy.deepcopy(self.__dict__ )
     UpperCamelCase_									=     self.vision_config.to_dict()
     UpperCamelCase_									=     self.__class__.model_type
     return output





