






import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import YolosForObjectDetection, YolosModel
 from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor



class 				_UpperCamelCase      :


      def __init__(						self       ,    __UpperCamelCase       ,    __UpperCamelCase=1_3       ,    __UpperCamelCase=[3_0, 3_0]       ,    __UpperCamelCase=2       ,    __UpperCamelCase=3       ,    __UpperCamelCase=True       ,    __UpperCamelCase=True       ,    __UpperCamelCase=3_2       ,    __UpperCamelCase=5       ,    __UpperCamelCase=4       ,    __UpperCamelCase=3_7       ,    __UpperCamelCase="gelu"       ,    __UpperCamelCase=0.1       ,    __UpperCamelCase=0.1       ,    __UpperCamelCase=1_0       ,    __UpperCamelCase=0.0_2       ,    __UpperCamelCase=3       ,    __UpperCamelCase=None       ,    __UpperCamelCase=8       ,    __UpperCamelCase=1_0       ,    )->						Any:
           __lowerCAmelCase             =       parent
           __lowerCAmelCase             =       batch_size
           __lowerCAmelCase             =       image_size
           __lowerCAmelCase             =       patch_size
           __lowerCAmelCase             =       num_channels
           __lowerCAmelCase             =       is_training
           __lowerCAmelCase             =       use_labels
           __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             =       type_sequence_label_size
           __lowerCAmelCase             =       initializer_range
           __lowerCAmelCase             =       num_labels
           __lowerCAmelCase             =       scope
           __lowerCAmelCase             =       n_targets
           __lowerCAmelCase             =       num_detection_tokens
           # we set the expected sequence length (which is used in several tests)
           # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
           __lowerCAmelCase             =       (image_size[1] // patch_size) * (image_size[0] // patch_size)
           __lowerCAmelCase             =       num_patches + 1 + self.num_detection_tokens


      def 			__UpperCAmelCase		(						self						)->						str:
           __lowerCAmelCase             =       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]						)

           __lowerCAmelCase             =       None
           if self.use_labels:
                # labels is a list of Dict (each Dict being the labels for a given example in the batch)
                __lowerCAmelCase             =       []
                for i in range(self.batch_size						):
                     __lowerCAmelCase             =       {}
                     __lowerCAmelCase             =       torch.randint(
                         high=self.num_labels       ,    size=(self.n_targets,)       ,    device=UpperCamelCase__						)
                     __lowerCAmelCase             =       torch.rand(self.n_targets       ,    4       ,    device=UpperCamelCase__						)
                     labels.append(UpperCamelCase__						)

           __lowerCAmelCase             =       self.get_config()

           return config, pixel_values, labels


      def 			__UpperCAmelCase		(						self						)->						Any:
           return YolosConfig(
               image_size=self.image_size       ,    patch_size=self.patch_size       ,    num_channels=self.num_channels       ,    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       ,    is_decoder=UpperCamelCase__       ,    initializer_range=self.initializer_range       ,    num_detection_tokens=self.num_detection_tokens       ,    num_labels=self.num_labels       ,    )


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase						)->						Optional[Any]:
           __lowerCAmelCase             =       YolosModel(config=UpperCamelCase__						)
           model.to(UpperCamelCase__						)
           model.eval()
           __lowerCAmelCase             =       model(UpperCamelCase__						)
           self.parent.assertEqual(
               result.last_hidden_state.shape       ,    (self.batch_size, self.expected_seq_len, self.hidden_size)						)


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase						)->						Any:
           __lowerCAmelCase             =       YolosForObjectDetection(UpperCamelCase__						)
           model.to(UpperCamelCase__						)
           model.eval()

           __lowerCAmelCase             =       model(pixel_values=UpperCamelCase__						)
           __lowerCAmelCase             =       model(UpperCamelCase__						)

           self.parent.assertEqual(result.logits.shape       ,    (self.batch_size, self.num_detection_tokens, self.num_labels + 1)						)
           self.parent.assertEqual(result.pred_boxes.shape       ,    (self.batch_size, self.num_detection_tokens, 4)						)

           __lowerCAmelCase             =       model(pixel_values=UpperCamelCase__       ,    labels=UpperCamelCase__						)

           self.parent.assertEqual(result.loss.shape       ,    ()						)
           self.parent.assertEqual(result.logits.shape       ,    (self.batch_size, self.num_detection_tokens, self.num_labels + 1)						)
           self.parent.assertEqual(result.pred_boxes.shape       ,    (self.batch_size, self.num_detection_tokens, 4)						)


      def 			__UpperCAmelCase		(						self						)->						Union[str, Any]:
           __lowerCAmelCase             =       self.prepare_config_and_inputs()
           __lowerCAmelCase      ,			__lowerCAmelCase      ,			__lowerCAmelCase             =       config_and_inputs
           __lowerCAmelCase             =       {"pixel_values": pixel_values}
           return config, inputs_dict



@require_torch
class 				_UpperCamelCase      (_UpperCamelCase				,		_UpperCamelCase				,		unittest.TestCase      ):
      snake_case_	=				(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
      snake_case_	=				(
          {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
      )

      snake_case_	=				False
      snake_case_	=				False
      snake_case_	=				False
      snake_case_	=				False


      def 			__UpperCAmelCase		(						self       ,    __UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase=False						)->						Union[str, Any]:
           __lowerCAmelCase             =       super()._prepare_for_class(UpperCamelCase__       ,    UpperCamelCase__       ,    return_labels=UpperCamelCase__						)

           if return_labels:
                if model_class.__name__ == "YolosForObjectDetection":
                     __lowerCAmelCase             =       []
                     for i in range(self.model_tester.batch_size						):
                          __lowerCAmelCase             =       {}
                          __lowerCAmelCase             =       torch.ones(
                              size=(self.model_tester.n_targets,)       ,    device=UpperCamelCase__       ,    dtype=torch.long						)
                          __lowerCAmelCase             =       torch.ones(
                              self.model_tester.n_targets       ,    4       ,    device=UpperCamelCase__       ,    dtype=torch.float						)
                          labels.append(UpperCamelCase__						)
                     __lowerCAmelCase             =       labels

           return inputs_dict


      def 			__UpperCAmelCase		(						self						)->						Dict:
           __lowerCAmelCase             =       YolosModelTester(self						)
           __lowerCAmelCase             =       ConfigTester(self       ,    config_class=UpperCamelCase__       ,    has_text_modality=UpperCamelCase__       ,    hidden_size=3_7						)


      def 			__UpperCAmelCase		(						self						)->						Optional[int]:
           self.config_tester.run_common_tests()


      def 			__UpperCAmelCase		(						self						)->						int:
           # YOLOS does not use inputs_embeds
           pass


      def 			__UpperCAmelCase		(						self						)->						str:
           __lowerCAmelCase      ,			__lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                __lowerCAmelCase             =       model_class(UpperCamelCase__						)
                self.assertIsInstance(model.get_input_embeddings()       ,    (nn.Module)						)
                __lowerCAmelCase             =       model.get_output_embeddings()
                self.assertTrue(x is None or isinstance(UpperCamelCase__       ,    nn.Linear						)						)


      def 			__UpperCAmelCase		(						self						)->						int:
           __lowerCAmelCase      ,			__lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                __lowerCAmelCase             =       model_class(UpperCamelCase__						)
                __lowerCAmelCase             =       inspect.signature(model.forward						)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                __lowerCAmelCase             =       [*signature.parameters.keys()]

                __lowerCAmelCase             =       ["pixel_values"]
                self.assertListEqual(arg_names[:1]       ,    UpperCamelCase__						)


      def 			__UpperCAmelCase		(						self						)->						Any:
           __lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase__						)


      def 			__UpperCAmelCase		(						self						)->						List[str]:
           __lowerCAmelCase      ,			__lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs_for_common()
           __lowerCAmelCase             =       True

           # in YOLOS, the seq_len is different
           __lowerCAmelCase             =       self.model_tester.expected_seq_len
           for model_class in self.all_model_classes:
                __lowerCAmelCase             =       True
                __lowerCAmelCase             =       False
                __lowerCAmelCase             =       True
                __lowerCAmelCase             =       model_class(UpperCamelCase__						)
                model.to(UpperCamelCase__						)
                model.eval()
                with torch.no_grad():
                     __lowerCAmelCase             =       model(**self._prepare_for_class(UpperCamelCase__       ,    UpperCamelCase__						)						)
                __lowerCAmelCase             =       outputs.attentions
                self.assertEqual(len(UpperCamelCase__						)       ,    self.model_tester.num_hidden_layers						)

                # check that output_attentions also work using config
                del inputs_dict["output_attentions"]
                __lowerCAmelCase             =       True
                __lowerCAmelCase             =       model_class(UpperCamelCase__						)
                model.to(UpperCamelCase__						)
                model.eval()
                with torch.no_grad():
                     __lowerCAmelCase             =       model(**self._prepare_for_class(UpperCamelCase__       ,    UpperCamelCase__						)						)
                __lowerCAmelCase             =       outputs.attentions
                self.assertEqual(len(UpperCamelCase__						)       ,    self.model_tester.num_hidden_layers						)

                self.assertListEqual(
                    list(attentions[0].shape[-3:]						)       ,    [self.model_tester.num_attention_heads, seq_len, seq_len]       ,    )
                __lowerCAmelCase             =       len(UpperCamelCase__						)

                # Check attention is always last and order is fine
                __lowerCAmelCase             =       True
                __lowerCAmelCase             =       True
                __lowerCAmelCase             =       model_class(UpperCamelCase__						)
                model.to(UpperCamelCase__						)
                model.eval()
                with torch.no_grad():
                     __lowerCAmelCase             =       model(**self._prepare_for_class(UpperCamelCase__       ,    UpperCamelCase__						)						)

                __lowerCAmelCase             =       1
                self.assertEqual(out_len + added_hidden_states       ,    len(UpperCamelCase__						)						)

                __lowerCAmelCase             =       outputs.attentions

                self.assertEqual(len(UpperCamelCase__						)       ,    self.model_tester.num_hidden_layers						)
                self.assertListEqual(
                    list(self_attentions[0].shape[-3:]						)       ,    [self.model_tester.num_attention_heads, seq_len, seq_len]       ,    )


      def 			__UpperCAmelCase		(						self						)->						Dict:
           def check_hidden_states_output(__UpperCamelCase       ,    __UpperCamelCase       ,    __UpperCamelCase						):
                __lowerCAmelCase             =       model_class(UpperCamelCase__						)
                model.to(UpperCamelCase__						)
                model.eval()

                with torch.no_grad():
                     __lowerCAmelCase             =       model(**self._prepare_for_class(UpperCamelCase__       ,    UpperCamelCase__						)						)

                __lowerCAmelCase             =       outputs.hidden_states

                __lowerCAmelCase             =       getattr(
                    self.model_tester       ,    "expected_num_hidden_layers"       ,    self.model_tester.num_hidden_layers + 1						)
                self.assertEqual(len(UpperCamelCase__						)       ,    UpperCamelCase__						)

                # YOLOS has a different seq_length
                __lowerCAmelCase             =       self.model_tester.expected_seq_len

                self.assertListEqual(
                    list(hidden_states[0].shape[-2:]						)       ,    [seq_length, self.model_tester.hidden_size]       ,    )

           __lowerCAmelCase      ,			__lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                __lowerCAmelCase             =       True
                check_hidden_states_output(UpperCamelCase__       ,    UpperCamelCase__       ,    UpperCamelCase__						)

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                __lowerCAmelCase             =       True

                check_hidden_states_output(UpperCamelCase__       ,    UpperCamelCase__       ,    UpperCamelCase__						)


      def 			__UpperCAmelCase		(						self						)->						Optional[Any]:
           __lowerCAmelCase             =       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_object_detection(*UpperCamelCase__						)


      @slow
      def 			__UpperCAmelCase		(						self						)->						str:
           for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                __lowerCAmelCase             =       YolosModel.from_pretrained(UpperCamelCase__						)
                self.assertIsNotNone(UpperCamelCase__						)





def    __lowerCAmelCase   (    ):
     __lowerCAmelCase             =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
     return image



@require_torch
@require_vision
class 				_UpperCamelCase      (unittest.TestCase      ):


      @cached_property
      def 			__UpperCAmelCase		(						self						)->						Any:
           return AutoImageProcessor.from_pretrained("hustvl/yolos-small"						) if is_vision_available() else None


      @slow
      def 			__UpperCAmelCase		(						self						)->						int:
           __lowerCAmelCase             =       YolosForObjectDetection.from_pretrained("hustvl/yolos-small"						).to(UpperCamelCase__						)

           __lowerCAmelCase             =       self.default_image_processor
           __lowerCAmelCase             =       prepare_img()
           __lowerCAmelCase             =       image_processor(images=UpperCamelCase__       ,    return_tensors="pt"						).to(UpperCamelCase__						)

           # forward pass
           with torch.no_grad():
                __lowerCAmelCase             =       model(inputs.pixel_values						)

           # verify outputs
           __lowerCAmelCase             =       torch.Size((1, 1_0_0, 9_2)						)
           self.assertEqual(outputs.logits.shape       ,    UpperCamelCase__						)

           __lowerCAmelCase             =       torch.tensor(
               [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]]       ,    device=UpperCamelCase__       ,    )
           __lowerCAmelCase             =       torch.tensor(
               [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]       ,    device=UpperCamelCase__						)
           self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]       ,    UpperCamelCase__       ,    atol=1e-4						)						)
           self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]       ,    UpperCamelCase__       ,    atol=1e-4						)						)

           # verify postprocessing
           __lowerCAmelCase             =       image_processor.post_process_object_detection(
               UpperCamelCase__       ,    threshold=0.3       ,    target_sizes=[image.size[::-1]]						)[0]
           __lowerCAmelCase             =       torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]						).to(UpperCamelCase__						)
           __lowerCAmelCase             =       [7_5, 7_5, 1_7, 6_3, 1_7]
           __lowerCAmelCase             =       torch.tensor([3_3_5.0_6_0_9, 7_9.3_8_4_8, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]						).to(UpperCamelCase__						)

           self.assertEqual(len(results["scores"]						)       ,    5						)
           self.assertTrue(torch.allclose(results["scores"]       ,    UpperCamelCase__       ,    atol=1e-4						)						)
           self.assertSequenceEqual(results["labels"].tolist()       ,    UpperCamelCase__						)
           self.assertTrue(torch.allclose(results["boxes"][0, :]       ,    UpperCamelCase__						)						)







'''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 lowercase_       :







   """simple docstring"""

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

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

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

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

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







@require_tf
class lowercase_       (		_UpperCamelCase    ,    _UpperCamelCase    ,    unittest.TestCase			):







   """simple docstring"""

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

   __lowerCAmelCase         =   False
   __lowerCAmelCase         =   False
   __lowerCAmelCase         =   False
   __lowerCAmelCase         =   False
   __lowerCAmelCase         =   False
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			Union[str, Any]:
        _A    		=  TFDPRModelTester(self     )
        _A    		=  ConfigTester(self, config_class=UpperCamelCase__, hidden_size=37     )
   def 	__UpperCAmelCase   (      self      :			List[str]     )  ->			Union[str, Any]:
        self.config_tester.run_common_tests()
   def 	__UpperCAmelCase   (      self      :			List[str]     )  ->			List[str]:
        _A    		=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_dpr_context_encoder(*UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			int     )  ->			List[str]:
        _A    		=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_dpr_question_encoder(*UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			int     )  ->			Tuple:
        _A    		=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_dpr_reader(*UpperCamelCase__     )

   @slow
   def 	__UpperCAmelCase   (      self      :			List[Any]     )  ->			Union[str, Any]:
        for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A    		=  TFDPRContextEncoder.from_pretrained(UpperCamelCase__     )
             self.assertIsNotNone(UpperCamelCase__     )

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

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

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







@require_tf
class lowercase_       (		unittest.TestCase			):







   """simple docstring"""

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

        _A    		=  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]
        _A    		=  model(UpperCamelCase__     )[0]  # embedding shape = (1, 768)
        # compare the actual values for a slice.
        _A    		=  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     )     )



