





'''simple docstring'''






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			: int			,			__snake_case			: List[Any]			,			__snake_case			: Any=13			,			__snake_case			: List[str]=7			,			__snake_case			: str=True			,			__snake_case			: Optional[int]=True			,			__snake_case			: List[Any]=True			,			__snake_case			: str=True			,			__snake_case			: Union[str, Any]=99			,			__snake_case			: Tuple=32			,			__snake_case			: Tuple=2			,			__snake_case			: Tuple=4			,			__snake_case			: str=37			,			__snake_case			: List[str]="gelu"			,			__snake_case			: Dict=0.1			,			__snake_case			: Optional[int]=0.1			,			__snake_case			: List[str]=5_12			,			__snake_case			: Dict=16			,			__snake_case			: str=2			,			__snake_case			: Dict=0.02			,			__snake_case			: Union[str, Any]=3			,			__snake_case			: List[str]=4			,			__snake_case			: Dict=None			,			__snake_case			: str=0			,			)				->      Tuple:
            _lowerCAmelCase							     =							parent
            _lowerCAmelCase							     =							batch_size
            _lowerCAmelCase							     =							seq_length
            _lowerCAmelCase							     =							is_training
            _lowerCAmelCase							     =							use_input_mask
            _lowerCAmelCase							     =							use_token_type_ids
            _lowerCAmelCase							     =							use_labels
            _lowerCAmelCase							     =							vocab_size
            _lowerCAmelCase							     =							hidden_size
            _lowerCAmelCase							     =							num_hidden_layers
            _lowerCAmelCase							     =							num_attention_heads
            _lowerCAmelCase							     =							intermediate_size
            _lowerCAmelCase							     =							hidden_act
            _lowerCAmelCase							     =							hidden_dropout_prob
            _lowerCAmelCase							     =							attention_probs_dropout_prob
            _lowerCAmelCase							     =							max_position_embeddings
            _lowerCAmelCase							     =							type_vocab_size
            _lowerCAmelCase							     =							type_sequence_label_size
            _lowerCAmelCase							     =							initializer_range
            _lowerCAmelCase							     =							num_labels
            _lowerCAmelCase							     =							num_choices
            _lowerCAmelCase							     =							scope
            _lowerCAmelCase							     =							projection_dim




      def 				lowercase__    (			self			: int  )				->      Any:
            _lowerCAmelCase							     =							ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size  )

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

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

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

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




      def 				lowercase__    (			self			: Optional[int]			,			__snake_case			: Dict			,			__snake_case			: str			,			__snake_case			: Tuple			,			__snake_case			: int			,			__snake_case			: List[str]			,			__snake_case			: str			,			__snake_case			: Any  )				->      str:
            _lowerCAmelCase							     =							TFDPRQuestionEncoder(config=__snake_case  )
            _lowerCAmelCase							     =							model(__snake_case			,			attention_mask=__snake_case			,			token_type_ids=__snake_case  )
            _lowerCAmelCase							     =							model(__snake_case			,			token_type_ids=__snake_case  )
            _lowerCAmelCase							     =							model(__snake_case  )
            self.parent.assertEqual(result.pooler_output.shape			,			(self.batch_size, self.projection_dim or self.hidden_size)  )




      def 				lowercase__    (			self			: Optional[int]			,			__snake_case			: int			,			__snake_case			: Optional[Any]			,			__snake_case			: List[Any]			,			__snake_case			: str			,			__snake_case			: Union[str, Any]			,			__snake_case			: Optional[int]			,			__snake_case			: Any  )				->      Optional[int]:
            _lowerCAmelCase							     =							TFDPRReader(config=__snake_case  )
            _lowerCAmelCase							     =							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			: List[str]  )				->      List[str]:
            _lowerCAmelCase							     =							self.prepare_config_and_inputs()
            (
                (
                _lowerCAmelCase
            )     ,							(
                _lowerCAmelCase
            )     ,							(
                _lowerCAmelCase
            )     ,							(
                _lowerCAmelCase
            )     ,							(
                _lowerCAmelCase
            )     ,							(
                _lowerCAmelCase
            )     ,							(
                _lowerCAmelCase
            )     ,							
            )							     =							config_and_inputs
            _lowerCAmelCase							     =							{"""input_ids""": input_ids}
            return config, inputs_dict




@require_tf
class  UpperCAmelCase     (			snake_case_							,		snake_case_							,		unittest.TestCase   ):
      _lowercase:			List[str]						     =   (
          (
              TFDPRContextEncoder,
              TFDPRQuestionEncoder,
              TFDPRReader,
          )
          if is_tf_available()
          else ()
      )
      _lowercase:			Optional[Any]						     =   {'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {}

      _lowercase:			str						     =   False
      _lowercase:			List[str]						     =   False
      _lowercase:			Dict						     =   False
      _lowercase:			Union[str, Any]						     =   False
      _lowercase:			Dict						     =   False




      def 				lowercase__    (			self			: Optional[Any]  )				->      Tuple:
            _lowerCAmelCase							     =							TFDPRModelTester(self  )
            _lowerCAmelCase							     =							ConfigTester(self			,			config_class=__snake_case			,			hidden_size=37  )




      def 				lowercase__    (			self			: str  )				->      List[Any]:
            self.config_tester.run_common_tests()




      def 				lowercase__    (			self			: Union[str, Any]  )				->      Union[str, Any]:
            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_dpr_context_encoder(*__snake_case  )




      def 				lowercase__    (			self			: Optional[Any]  )				->      List[Any]:
            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_dpr_question_encoder(*__snake_case  )




      def 				lowercase__    (			self			: int  )				->      Union[str, Any]:
            _lowerCAmelCase							     =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_dpr_reader(*__snake_case  )




      @slow
      def 				lowercase__    (			self			: Any  )				->      Tuple:
            for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _lowerCAmelCase							     =							TFDPRContextEncoder.from_pretrained(__snake_case  )
                  self.assertIsNotNone(__snake_case  )

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

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

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




@require_tf
class  UpperCAmelCase     (			unittest.TestCase   ):




      @slow
      def 				lowercase__    (			self			: Optional[Any]  )				->      str:
            _lowerCAmelCase							     =							TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""  )

            _lowerCAmelCase							     =							tf.constant(
                [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]]  )  # [CLS] hello, is my dog cute? [SEP]
            _lowerCAmelCase							     =							model(__snake_case  )[0]  # embedding shape = (1, 768)
            # compare the actual values for a slice.
            _lowerCAmelCase							     =							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[:, :10].numpy()			,			expected_slice.numpy()			,			atol=1E-4  )  )











'''simple docstring'''




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCamelCase__       :	Any    = {
    '''configuration_instructblip''': [
        '''INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''InstructBlipConfig''',
        '''InstructBlipQFormerConfig''',
        '''InstructBlipVisionConfig''',
    ],
    '''processing_instructblip''': ['''InstructBlipProcessor'''],
}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						UpperCamelCase__       :	Optional[Any]    = [
						    '''INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
						    '''InstructBlipQFormerModel''',
						    '''InstructBlipPreTrainedModel''',
						    '''InstructBlipForConditionalGeneration''',
						    '''InstructBlipVisionModel''',
						]

if TYPE_CHECKING:
						from .configuration_instructblip import (
						    INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
						    InstructBlipConfig,
						    InstructBlipQFormerConfig,
						    InstructBlipVisionConfig,
						)
						from .processing_instructblip import InstructBlipProcessor

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_instructblip import (
												    INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
												    InstructBlipForConditionalGeneration,
												    InstructBlipPreTrainedModel,
												    InstructBlipQFormerModel,
												    InstructBlipVisionModel,
												)

else:
						import sys

						UpperCamelCase__       :	str    = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)