

"""simple docstring"""

import tempfile
import unittest

from transformers import DPRConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import DPRContextEncoder, DPRQuestionEncoder, DPRReader, DPRReaderTokenizer
							from transformers.models.dpr.modeling_dpr import (
							    DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
							    DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
							    DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
							)


class       _snake_case  :







						def __init__(self  ,				UpperCAmelCase_  ,				UpperCAmelCase_=1_3  ,				UpperCAmelCase_=7  ,				UpperCAmelCase_=False  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=9_9  ,				UpperCAmelCase_=3_2  ,				UpperCAmelCase_=5  ,				UpperCAmelCase_=4  ,				UpperCAmelCase_=3_7  ,				UpperCAmelCase_="gelu"  ,				UpperCAmelCase_=0.1  ,				UpperCAmelCase_=0.1  ,				UpperCAmelCase_=5_1_2  ,				UpperCAmelCase_=1_6  ,				UpperCAmelCase_=2  ,				UpperCAmelCase_=0.0_2  ,				UpperCAmelCase_=3  ,				UpperCAmelCase_=4  ,				UpperCAmelCase_=None  ,				UpperCAmelCase_=0  ,				)      ->    List[str]:
											__lowercase        =      parent
											__lowercase        =      batch_size
											__lowercase        =      seq_length
											__lowercase        =      is_training
											__lowercase        =      use_input_mask
											__lowercase        =      use_token_type_ids
											__lowercase        =      use_labels
											__lowercase        =      vocab_size
											__lowercase        =      hidden_size
											__lowercase        =      num_hidden_layers
											__lowercase        =      num_attention_heads
											__lowercase        =      intermediate_size
											__lowercase        =      hidden_act
											__lowercase        =      hidden_dropout_prob
											__lowercase        =      attention_probs_dropout_prob
											__lowercase        =      max_position_embeddings
											__lowercase        =      type_vocab_size
											__lowercase        =      type_sequence_label_size
											__lowercase        =      initializer_range
											__lowercase        =      num_labels
											__lowercase        =      num_choices
											__lowercase        =      scope
											__lowercase        =      projection_dim







						def 							_UpperCamelCase     (self				)      ->    Union[str, Any]:
											__lowercase        =      ids_tensor([self.batch_size, self.seq_length]  ,				self.vocab_size				)

											__lowercase        =      None
											if self.use_input_mask:
																__lowercase        =      random_attention_mask([self.batch_size, self.seq_length]				)

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

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

											__lowercase        =      self.get_config()

											return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







						def 							_UpperCamelCase     (self				)      ->    int:
											return DPRConfig(
											    projection_dim=self.projection_dim  ,				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  ,				initializer_range=self.initializer_range  ,				)







						def 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_				)      ->    Dict:
											__lowercase        =      DPRContextEncoder(config=lowercase_				)
											model.to(lowercase_				)
											model.eval()
											__lowercase        =      model(lowercase_  ,				attention_mask=lowercase_  ,				token_type_ids=lowercase_				)
											__lowercase        =      model(lowercase_  ,				token_type_ids=lowercase_				)
											__lowercase        =      model(lowercase_				)
											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_				)      ->    str:
											__lowercase        =      DPRQuestionEncoder(config=lowercase_				)
											model.to(lowercase_				)
											model.eval()
											__lowercase        =      model(lowercase_  ,				attention_mask=lowercase_  ,				token_type_ids=lowercase_				)
											__lowercase        =      model(lowercase_  ,				token_type_ids=lowercase_				)
											__lowercase        =      model(lowercase_				)
											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]:
											__lowercase        =      DPRReader(config=lowercase_				)
											model.to(lowercase_				)
											model.eval()
											__lowercase        =      model(
											    lowercase_  ,				attention_mask=lowercase_  ,				)

											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:
											__lowercase        =      self.prepare_config_and_inputs()
											(
											    __lowercase			
											)        =      config_and_inputs
											__lowercase        =      {"input_ids": input_ids}
											return config, inputs_dict



@require_torch
class       _snake_case  (    snake_case__    ,      snake_case__    ,      unittest.TestCase							):
						__snake_case			      =  (
						    (
						        DPRContextEncoder,
						        DPRQuestionEncoder,
						        DPRReader,
						    )
						    if is_torch_available()
						    else ()
						)
						__snake_case			      =  {'feature-extraction': DPRQuestionEncoder} if is_torch_available() else {}

						__snake_case			      =  False
						__snake_case			      =  False  # why?
						__snake_case			      =  False
						__snake_case			      =  False







						def 							_UpperCamelCase     (self				)      ->    str:
											__lowercase        =      DPRModelTester(self				)
											__lowercase        =      ConfigTester(self  ,				config_class=lowercase_  ,				hidden_size=3_7				)







						def 							_UpperCamelCase     (self				)      ->    str:
											self.config_tester.run_common_tests()







						def 							_UpperCamelCase     (self				)      ->    Tuple:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_context_encoder(*lowercase_				)







						def 							_UpperCamelCase     (self				)      ->    Union[str, Any]:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_question_encoder(*lowercase_				)







						def 							_UpperCamelCase     (self				)      ->    List[Any]:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_reader(*lowercase_				)







						def 							_UpperCamelCase     (self				)      ->    Optional[Any]:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()[0]

											__lowercase        =      DPRQuestionEncoder(config=lowercase_				)
											model.to(lowercase_				)
											model.eval()

											with tempfile.TemporaryDirectory() as tmp_dirname:
																model.save_pretrained(lowercase_				)
																__lowercase        =      DPRQuestionEncoder.from_pretrained(lowercase_  ,				projection_dim=5_1_2				)

											self.assertIsNotNone(lowercase_				)







						@slow
						def 							_UpperCamelCase     (self				)      ->    List[str]:
											for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__lowercase        =      DPRContextEncoder.from_pretrained(lowercase_				)
																self.assertIsNotNone(lowercase_				)

											for model_name in DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__lowercase        =      DPRContextEncoder.from_pretrained(lowercase_				)
																self.assertIsNotNone(lowercase_				)

											for model_name in DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__lowercase        =      DPRQuestionEncoder.from_pretrained(lowercase_				)
																self.assertIsNotNone(lowercase_				)

											for model_name in DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__lowercase        =      DPRReader.from_pretrained(lowercase_				)
																self.assertIsNotNone(lowercase_				)



@require_torch
class       _snake_case  (    unittest.TestCase							):







						@slow
						def 							_UpperCamelCase     (self				)      ->    Optional[Any]:
											__lowercase        =      DPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base'''  ,				return_dict=lowercase_				)
											model.to(lowercase_				)

											__lowercase        =      torch.tensor(
											    [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]]  ,				dtype=torch.long  ,				device=lowercase_				)  # [CLS] hello, is my dog cute? [SEP]
											__lowercase        =      model(lowercase_				)[0]  # embedding shape = (1, 768)
											# compare the actual values for a slice.
											__lowercase        =      torch.tensor(
											    [
											        [
											            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,
											        ]
											    ]  ,				dtype=torch.float  ,				device=lowercase_  ,				)
											self.assertTrue(torch.allclose(output[:, :1_0]  ,				lowercase_  ,				atol=1e-4				)				)







						@slow
						def 							_UpperCamelCase     (self				)      ->    List[str]:
											__lowercase        =      DPRReaderTokenizer.from_pretrained('''facebook/dpr-reader-single-nq-base'''				)
											__lowercase        =      DPRReader.from_pretrained('''facebook/dpr-reader-single-nq-base'''				)
											model.to(lowercase_				)

											__lowercase        =      tokenizer(
											    questions='''What is love ?'''  ,				titles='''Haddaway'''  ,				texts='''What Is Love is a song recorded by the artist Haddaway'''  ,				padding=lowercase_  ,				return_tensors='''pt'''  ,				)
											encoded_inputs.to(lowercase_				)

											__lowercase        =      model(**lowercase_				)

											# compare the actual values for a slice.
											__lowercase        =      torch.tensor(
											    [[-1_0.3_0_0_5, -1_0.7_7_6_5, -1_1.4_8_7_2, -1_1.6_8_4_1, -1_1.9_3_1_2, -1_0.3_0_0_2, -9.8_5_4_4, -1_1.7_3_7_8, -1_2.0_8_2_1, -1_0.2_9_7_5]]  ,				dtype=torch.float  ,				device=lowercase_  ,				)

											__lowercase        =      torch.tensor(
											    [[-1_1.0_6_8_4, -1_1.7_0_4_1, -1_1.5_3_9_7, -1_0.3_4_6_5, -1_0.8_7_9_1, -6.8_4_4_3, -1_1.9_9_5_9, -1_1.0_3_6_4, -1_0.0_0_9_6, -6.8_4_0_5]]  ,				dtype=torch.float  ,				device=lowercase_  ,				)
											self.assertTrue(torch.allclose(outputs.start_logits[:, :1_0]  ,				lowercase_  ,				atol=1e-4				)				)
											self.assertTrue(torch.allclose(outputs.end_logits[:, :1_0]  ,				lowercase_  ,				atol=1e-4				)				)




'''simple docstring'''
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


a_           =    {
    "configuration_sam": [
        "SAM_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "SamConfig",
        "SamMaskDecoderConfig",
        "SamPromptEncoderConfig",
        "SamVisionConfig",
    ],
    "processing_sam": ["SamProcessor"],
}


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  a_           =    [
      "SAM_PRETRAINED_MODEL_ARCHIVE_LIST",
      "SamModel",
      "SamPreTrainedModel",
  ]
try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  a_           =    [
      "TF_SAM_PRETRAINED_MODEL_ARCHIVE_LIST",
      "TFSamModel",
      "TFSamPreTrainedModel",
  ]
try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  a_           =    ["SamImageProcessor"]


if TYPE_CHECKING:
  from .configuration_sam import (
      SAM_PRETRAINED_CONFIG_ARCHIVE_MAP,
      SamConfig,
      SamMaskDecoderConfig,
      SamPromptEncoderConfig,
      SamVisionConfig,
  )
  from .processing_sam import SamProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_sam import SAM_PRETRAINED_MODEL_ARCHIVE_LIST, SamModel, SamPreTrainedModel

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_sam import TF_SAM_PRETRAINED_MODEL_ARCHIVE_LIST, TFSamModel, TFSamPreTrainedModel

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_sam import SamImageProcessor

else:
  import sys

  a_           =    _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




