



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

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

          UpperCamelCase       :    Union[str, Any]		      =      None
          if self.use_token_type_ids:
             UpperCamelCase       :    List[Any]		      =      ids_tensor([self.batch_size, self.seq_length],     self.type_vocab_size			)

          UpperCamelCase       :    str		      =      None
          UpperCamelCase       :    Any		      =      None
          UpperCamelCase       :    int		      =      None
          if self.use_labels:
             UpperCamelCase       :    Dict		      =      ids_tensor([self.batch_size],     self.type_sequence_label_size			)
             UpperCamelCase       :    int		      =      ids_tensor([self.batch_size, self.seq_length],     self.num_labels			)
             UpperCamelCase       :    List[str]		      =      ids_tensor([self.batch_size],     self.num_choices			)

          UpperCamelCase       :    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=SCREAMING_SNAKE_CASE_,     initializer_range=self.initializer_range,     )
          UpperCamelCase       :    str		      =      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    snake_case_			(     self,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_			)	->						Any:
          UpperCamelCase       :    Optional[Any]		      =      TFDPRContextEncoder(config=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    List[str]		      =      model(SCREAMING_SNAKE_CASE_,     attention_mask=SCREAMING_SNAKE_CASE_,     token_type_ids=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    Any		      =      model(SCREAMING_SNAKE_CASE_,     token_type_ids=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    Union[str, Any]		      =      model(SCREAMING_SNAKE_CASE_			)
          self.parent.assertEqual(result.pooler_output.shape,     (self.batch_size, self.projection_dim or self.hidden_size)			)
       def    snake_case_			(     self,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_			)	->						List[str]:
          UpperCamelCase       :    Dict		      =      TFDPRQuestionEncoder(config=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    Optional[int]		      =      model(SCREAMING_SNAKE_CASE_,     attention_mask=SCREAMING_SNAKE_CASE_,     token_type_ids=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    Optional[Any]		      =      model(SCREAMING_SNAKE_CASE_,     token_type_ids=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    List[str]		      =      model(SCREAMING_SNAKE_CASE_			)
          self.parent.assertEqual(result.pooler_output.shape,     (self.batch_size, self.projection_dim or self.hidden_size)			)
       def    snake_case_			(     self,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_			)	->						Any:
          UpperCamelCase       :    Tuple		      =      TFDPRReader(config=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    List[Any]		      =      model(SCREAMING_SNAKE_CASE_,     attention_mask=SCREAMING_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    snake_case_			(     self			)	->						Any:
          UpperCamelCase       :    Any		      =      self.prepare_config_and_inputs()
          (
              (
              UpperCamelCase
          )      ,	(
              UpperCamelCase
          )      ,	(
              UpperCamelCase
          )      ,	(
              UpperCamelCase
          )      ,	(
              UpperCamelCase
          )      ,	(
              UpperCamelCase
          )      ,	(
              UpperCamelCase
          )      ,	
          )       :    Tuple		      =      config_and_inputs
          UpperCamelCase       :    Optional[Any]		      =      {'input_ids': input_ids}
          return config, inputs_dict






@require_tf
class 							lowerCAmelCase_						(    a__			,       a__			,       unittest.TestCase				):
       UpperCAmelCase__							:   List[Any]  	=    (
           (
               TFDPRContextEncoder,
               TFDPRQuestionEncoder,
               TFDPRReader,
           )
           if is_tf_available()
           else ()
       )
       UpperCAmelCase__							:   List[Any]  	=    {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}

       UpperCAmelCase__							:   int  	=    False
       UpperCAmelCase__							:   str  	=    False
       UpperCAmelCase__							:   Any  	=    False
       UpperCAmelCase__							:   Optional[int]  	=    False
       UpperCAmelCase__							:   Any  	=    False
       def    snake_case_			(     self			)	->						str:
          UpperCamelCase       :    Tuple		      =      TFDPRModelTester(self			)
          UpperCamelCase       :    Tuple		      =      ConfigTester(self,     config_class=SCREAMING_SNAKE_CASE_,     hidden_size=37			)
       def    snake_case_			(     self			)	->						Any:
          self.config_tester.run_common_tests()
       def    snake_case_			(     self			)	->						Union[str, Any]:
          UpperCamelCase       :    Any		      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_dpr_context_encoder(*SCREAMING_SNAKE_CASE_			)
       def    snake_case_			(     self			)	->						Optional[Any]:
          UpperCamelCase       :    Optional[int]		      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_dpr_question_encoder(*SCREAMING_SNAKE_CASE_			)
       def    snake_case_			(     self			)	->						Any:
          UpperCamelCase       :    Tuple		      =      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_dpr_reader(*SCREAMING_SNAKE_CASE_			)






       @slow
       def    snake_case_			(     self			)	->						List[str]:
          for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase       :    Any		      =      TFDPRContextEncoder.from_pretrained(SCREAMING_SNAKE_CASE_			)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)

          for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase       :    List[Any]		      =      TFDPRContextEncoder.from_pretrained(SCREAMING_SNAKE_CASE_			)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)

          for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase       :    List[Any]		      =      TFDPRQuestionEncoder.from_pretrained(SCREAMING_SNAKE_CASE_			)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)

          for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase       :    Optional[int]		      =      TFDPRReader.from_pretrained(SCREAMING_SNAKE_CASE_			)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)






@require_tf
class 							lowerCAmelCase_						(    unittest.TestCase				):
       @slow
       def    snake_case_			(     self			)	->						Any:
          UpperCamelCase       :    Union[str, Any]		      =      TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'			)

          UpperCamelCase       :    Dict		      =      tf.constant(
              [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]			)  # [CLS] hello, is my dog cute? [SEP]
          UpperCamelCase       :    Tuple		      =      model(SCREAMING_SNAKE_CASE_			)[0]  # embedding shape = (1, 768)
          # compare the actual values for a slice.
          UpperCamelCase       :    List[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[:, :10].numpy(),     expected_slice.numpy(),     atol=1e-4			)			)






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_lowerCAmelCase  :      Tuple			 ={
    """configuration_mobilenet_v2""": [
        """MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """MobileNetV2Config""",
        """MobileNetV2OnnxConfig""",
    ],
}

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_lowerCAmelCase  :      Tuple			 =["""MobileNetV2FeatureExtractor"""]
					_lowerCAmelCase  :      Optional[int]			 =["""MobileNetV2ImageProcessor"""]


try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_lowerCAmelCase  :      List[str]			 =[
					    """MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST""",
					    """MobileNetV2ForImageClassification""",
					    """MobileNetV2ForSemanticSegmentation""",
					    """MobileNetV2Model""",
					    """MobileNetV2PreTrainedModel""",
					    """load_tf_weights_in_mobilenet_v2""",
					]


if TYPE_CHECKING:
					from .configuration_mobilenet_va import (
					    MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP,
					    MobileNetVaConfig,
					    MobileNetVaOnnxConfig,
					)

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor
										from .image_processing_mobilenet_va import MobileNetVaImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_mobilenet_va import (
										    MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
										    MobileNetVaForImageClassification,
										    MobileNetVaForSemanticSegmentation,
										    MobileNetVaModel,
										    MobileNetVaPreTrainedModel,
										    load_tf_weights_in_mobilenet_va,
										)


else:
					import sys

					_lowerCAmelCase  :      Any			 =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)