






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					,						__UpperCamelCase					,						__UpperCamelCase=1_3					,						__UpperCamelCase=7					,						__UpperCamelCase=True					,						__UpperCamelCase=True					,						__UpperCamelCase=True					,						__UpperCamelCase=True					,						__UpperCamelCase=9_9					,						__UpperCamelCase=3_2					,						__UpperCamelCase=2					,						__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[Any]:
           __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  __UpperCAmelCase		(	self	)->	Dict:
           __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=_lowercase					,						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  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase	)->	Dict:
           __lowerCAmelCase								=					TFDPRContextEncoder(config=_lowercase	)
           __lowerCAmelCase								=					model(_lowercase					,						attention_mask=_lowercase					,						token_type_ids=_lowercase	)
           __lowerCAmelCase								=					model(_lowercase					,						token_type_ids=_lowercase	)
           __lowerCAmelCase								=					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	)->	Any:
           __lowerCAmelCase								=					TFDPRQuestionEncoder(config=_lowercase	)
           __lowerCAmelCase								=					model(_lowercase					,						attention_mask=_lowercase					,						token_type_ids=_lowercase	)
           __lowerCAmelCase								=					model(_lowercase					,						token_type_ids=_lowercase	)
           __lowerCAmelCase								=					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	)->	Optional[int]:
           __lowerCAmelCase								=					TFDPRReader(config=_lowercase	)
           __lowerCAmelCase								=					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	)->	List[Any]:
           __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			(UpperCAmelCase_							,		UpperCAmelCase_							,		unittest.TestCase			):
      snake_case_  =							(
          (
              TFDPRContextEncoder,
              TFDPRQuestionEncoder,
              TFDPRReader,
          )
          if is_tf_available()
          else ()
      )
      snake_case_  =							{"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

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


      def  __UpperCAmelCase		(	self	)->	List[Any]:
           __lowerCAmelCase								=					TFDPRModelTester(self	)
           __lowerCAmelCase								=					ConfigTester(self					,						config_class=_lowercase					,						hidden_size=3_7	)


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


      def  __UpperCAmelCase		(	self	)->	int:
           __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_dpr_context_encoder(*_lowercase	)


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


      def  __UpperCAmelCase		(	self	)->	List[Any]:
           __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_dpr_reader(*_lowercase	)


      @slow
      def  __UpperCAmelCase		(	self	)->	str:
           for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                __lowerCAmelCase								=					TFDPRContextEncoder.from_pretrained(_lowercase	)
                self.assertIsNotNone(_lowercase	)

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

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

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



@require_tf
class 							_UpperCamelCase			(unittest.TestCase			):


      @slow
      def  __UpperCAmelCase		(	self	)->	Optional[int]:
           __lowerCAmelCase								=					TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base"	)

           __lowerCAmelCase								=					tf.constant(
               [[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]]	)  # [CLS] hello, is my dog cute? [SEP]
           __lowerCAmelCase								=					model(_lowercase	)[0]  # embedding shape = (1, 768)
           # compare the actual values for a slice.
           __lowerCAmelCase								=					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[:, :1_0].numpy()					,						expected_slice.numpy()					,						atol=1e-4	)	)














import os
import sys
import unittest


lowerCamelCase			:					int         =	os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
lowerCamelCase			:					Any         =	os.path.join(git_repo_path, '''src''', '''diffusers''')



class 							_UpperCamelCase			(unittest.TestCase			):


      def  __UpperCAmelCase		(	self	)->	Optional[int]:
           __lowerCAmelCase								=					find_backend("    if not is_torch_available():"	)
           self.assertEqual(__UpperCamelCase					,						"torch"	)

           # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
           # self.assertEqual(backend_with_underscore, "tensorflow_text")

           __lowerCAmelCase								=					find_backend("    if not (is_torch_available() and is_transformers_available()):"	)
           self.assertEqual(__UpperCamelCase					,						"torch_and_transformers"	)

           # double_backend_with_underscore = find_backend(
           #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
           # )
           # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

           __lowerCAmelCase								=					find_backend(
               "    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):"	)
           self.assertEqual(__UpperCamelCase					,						"torch_and_transformers_and_onnx"	)


      def  __UpperCAmelCase		(	self	)->	Dict:
           __lowerCAmelCase								=					read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn("torch"					,						__UpperCamelCase	)
           self.assertIn("torch_and_transformers"					,						__UpperCamelCase	)
           self.assertIn("flax_and_transformers"					,						__UpperCamelCase	)
           self.assertIn("torch_and_transformers_and_onnx"					,						__UpperCamelCase	)

           # Likewise, we can't assert on the exact content of a key
           self.assertIn("UNet2DModel"					,						objects["torch"]	)
           self.assertIn("FlaxUNet2DConditionModel"					,						objects["flax"]	)
           self.assertIn("StableDiffusionPipeline"					,						objects["torch_and_transformers"]	)
           self.assertIn("FlaxStableDiffusionPipeline"					,						objects["flax_and_transformers"]	)
           self.assertIn("LMSDiscreteScheduler"					,						objects["torch_and_scipy"]	)
           self.assertIn("OnnxStableDiffusionPipeline"					,						objects["torch_and_transformers_and_onnx"]	)


      def  __UpperCAmelCase		(	self	)->	Any:
           __lowerCAmelCase								=					create_dummy_object("CONSTANT"					,						"'torch'"	)
           self.assertEqual(__UpperCamelCase					,						"\nCONSTANT = None\n"	)

           __lowerCAmelCase								=					create_dummy_object("function"					,						"'torch'"	)
           self.assertEqual(
               __UpperCamelCase					,						"\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"	)

           __lowerCAmelCase								=					"\nclass FakeClass(metaclass=DummyObject):\n    _backends = 'torch'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, 'torch')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n"
           __lowerCAmelCase								=					create_dummy_object("FakeClass"					,						"'torch'"	)
           self.assertEqual(__UpperCamelCase					,						__UpperCamelCase	)


      def  __UpperCAmelCase		(	self	)->	Tuple:
           __lowerCAmelCase								=					"# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = [\"torch\"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, [\"torch\"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n"
           __lowerCAmelCase								=					create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]}	)
           self.assertEqual(dummy_files["torch"]					,						__UpperCamelCase	)






