"""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	,    a	,    a=1_3	,    a=7	,    a=True	,    a=True	,    a=True	,    a=True	,    a=9_9	,    a=3_2	,    a=2	,    a=4	,    a=3_7	,    a="gelu"	,    a=0.1	,    a=0.1	,    a=5_1_2	,    a=1_6	,    a=2	,    a=0.02	,    a=3	,    a=4	,    a=None	,    a=0	,    ) ->      str:
             lowercase__    :	List[str]     					=			parent
             lowercase__    :	List[str]     					=			batch_size
             lowercase__    :	Optional[int]     					=			seq_length
             lowercase__    :	Any     					=			is_training
             lowercase__    :	Tuple     					=			use_input_mask
             lowercase__    :	Optional[Any]     					=			use_token_type_ids
             lowercase__    :	Union[str, Any]     					=			use_labels
             lowercase__    :	List[str]     					=			vocab_size
             lowercase__    :	Any     					=			hidden_size
             lowercase__    :	List[Any]     					=			num_hidden_layers
             lowercase__    :	List[str]     					=			num_attention_heads
             lowercase__    :	Optional[int]     					=			intermediate_size
             lowercase__    :	Dict     					=			hidden_act
             lowercase__    :	Dict     					=			hidden_dropout_prob
             lowercase__    :	Tuple     					=			attention_probs_dropout_prob
             lowercase__    :	str     					=			max_position_embeddings
             lowercase__    :	Optional[int]     					=			type_vocab_size
             lowercase__    :	Optional[int]     					=			type_sequence_label_size
             lowercase__    :	Tuple     					=			initializer_range
             lowercase__    :	List[Any]     					=			num_labels
             lowercase__    :	List[str]     					=			num_choices
             lowercase__    :	int     					=			scope
             lowercase__    :	int     					=			projection_dim


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

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

             lowercase__    :	Optional[Any]     					=			None
             if self.use_token_type_ids:
                    lowercase__    :	int     					=			ids_tensor([self.batch_size, self.seq_length]	,    self.type_vocab_size							)

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

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


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


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Tuple:
             lowercase__    :	int     					=			TFDPRReader(config=a							)
             lowercase__    :	Union[str, Any]     					=			model(a	,    attention_mask=a							)

             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]:
             lowercase__    :	int     					=			self.prepare_config_and_inputs()
             (
                 (
                 lowercase__
             )					,   (
                 lowercase__
             )					,   (
                 lowercase__
             )					,   (
                 lowercase__
             )					,   (
                 lowercase__
             )					,   (
                 lowercase__
             )					,   (
                 lowercase__
             )					,   
             )    :	Any     					=			config_and_inputs
             lowercase__    :	Optional[Any]     					=			{'input_ids': input_ids}
             return config, inputs_dict





@require_tf
class   UpperCAmelCase_			(					_a				,							_a				,							unittest.TestCase):
      lowerCamelCase__	:					str										=						(
          (
              TFDPRContextEncoder,
              TFDPRQuestionEncoder,
              TFDPRReader,
          )
          if is_tf_available()
          else ()
      )
      lowerCamelCase__	:					List[str]										=						{"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}

      lowerCamelCase__	:					Any										=						False
      lowerCamelCase__	:					Union[str, Any]										=						False
      lowerCamelCase__	:					Tuple										=						False
      lowerCamelCase__	:					Optional[Any]										=						False
      lowerCamelCase__	:					int										=						False


      def 	_UpperCAmelCase (     self							) ->      int:
             lowercase__    :	Tuple     					=			TFDPRModelTester(self							)
             lowercase__    :	str     					=			ConfigTester(self	,    config_class=a	,    hidden_size=3_7							)


      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             self.config_tester.run_common_tests()


      def 	_UpperCAmelCase (     self							) ->      int:
             lowercase__    :	str     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_dpr_context_encoder(*a							)


      def 	_UpperCAmelCase (     self							) ->      List[Any]:
             lowercase__    :	int     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_dpr_question_encoder(*a							)


      def 	_UpperCAmelCase (     self							) ->      Union[str, Any]:
             lowercase__    :	Tuple     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_dpr_reader(*a							)


      @slow
      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__    :	List[Any]     					=			TFDPRContextEncoder.from_pretrained(a							)
                    self.assertIsNotNone(a							)

             for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__    :	Tuple     					=			TFDPRContextEncoder.from_pretrained(a							)
                    self.assertIsNotNone(a							)

             for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__    :	Union[str, Any]     					=			TFDPRQuestionEncoder.from_pretrained(a							)
                    self.assertIsNotNone(a							)

             for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__    :	Tuple     					=			TFDPRReader.from_pretrained(a							)
                    self.assertIsNotNone(a							)





@require_tf
class   UpperCAmelCase_			(					unittest.TestCase):


      @slow
      def 	_UpperCAmelCase (     self							) ->      Tuple:
             lowercase__    :	Any     					=			TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'							)

             lowercase__    :	List[Any]     					=			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]
             lowercase__    :	Optional[int]     					=			model(a							)[0]  # embedding shape = (1, 768)
             # compare the actual values for a slice.
             lowercase__    :	Tuple     					=			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[:, :1_0].numpy()	,    expected_slice.numpy()	,    atol=1e-4							)							)


"""simple docstring"""





import unittest

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


if is_torch_available():
       import torch

       from transformers import AutoModelForImageClassification

if is_vision_available():
       from transformers import AutoImageProcessor


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


      @slow
      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	Optional[Any]     					=			AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'							)
             lowercase__    :	Union[str, Any]     					=			AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'							)
             model.to(a							)

             from datasets import load_dataset

             lowercase__    :	str     					=			load_dataset('nielsr/rvlcdip-demo'							)

             lowercase__    :	Tuple     					=			dataset['train'][0]['image'].convert('RGB'							)

             lowercase__    :	int     					=			image_processor(a	,    return_tensors='pt'							).to(a							)

             # forward pass
             with torch.no_grad():
                    lowercase__    :	List[str]     					=			model(**a							)
                    lowercase__    :	List[Any]     					=			outputs.logits

             lowercase__    :	Union[str, Any]     					=			torch.Size((1, 1_6)							)
             self.assertEqual(logits.shape	,    a							)

             lowercase__    :	Tuple     					=			torch.tensor(
                 [-0.4_158, -0.4_092, -0.4_347]	,    device=a	,    dtype=torch.float	,    )
             self.assertTrue(torch.allclose(logits[0, :3]	,    a	,    atol=1e-4							)							)

