
"""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  ,     snake_case__  ,     snake_case__=13  ,     snake_case__=7  ,     snake_case__=True  ,     snake_case__=True  ,     snake_case__=True  ,     snake_case__=True  ,     snake_case__=99  ,     snake_case__=32  ,     snake_case__=2  ,     snake_case__=4  ,     snake_case__=37  ,     snake_case__="gelu"  ,     snake_case__=0.1  ,     snake_case__=0.1  ,     snake_case__=512  ,     snake_case__=16  ,     snake_case__=2  ,     snake_case__=0.02  ,     snake_case__=3  ,     snake_case__=4  ,     snake_case__=None  ,     snake_case__=0  ,     ):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				str							    = parent
       _SCREAMING_SNAKE_CASE   :				int							    = batch_size
       _SCREAMING_SNAKE_CASE   :				str							    = seq_length
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = is_training
       _SCREAMING_SNAKE_CASE   :				Dict							    = use_input_mask
       _SCREAMING_SNAKE_CASE   :				str							    = use_token_type_ids
       _SCREAMING_SNAKE_CASE   :				Tuple							    = use_labels
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = vocab_size
       _SCREAMING_SNAKE_CASE   :				List[str]							    = hidden_size
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = num_hidden_layers
       _SCREAMING_SNAKE_CASE   :				str							    = num_attention_heads
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = intermediate_size
       _SCREAMING_SNAKE_CASE   :				Dict							    = hidden_act
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = hidden_dropout_prob
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = attention_probs_dropout_prob
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = max_position_embeddings
       _SCREAMING_SNAKE_CASE   :				str							    = type_vocab_size
       _SCREAMING_SNAKE_CASE   :				Any							    = type_sequence_label_size
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = initializer_range
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = num_labels
       _SCREAMING_SNAKE_CASE   :				int							    = num_choices
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = scope
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = projection_dim
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Any							    = ids_tensor([self.batch_size, self.seq_length]  ,     self.vocab_size				)

       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = None
       if self.use_input_mask:
         # follow test_modeling_tf_ctrl.py
         _SCREAMING_SNAKE_CASE   :				Optional[int]							    = random_attention_mask([self.batch_size, self.seq_length]				)

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

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

       _SCREAMING_SNAKE_CASE   :				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=snake_case__  ,     initializer_range=self.initializer_range  ,     )
       _SCREAMING_SNAKE_CASE   :				Tuple							    = 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 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Any							    = TFDPRContextEncoder(config=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = model(snake_case__  ,     attention_mask=snake_case__  ,     token_type_ids=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				int							    = model(snake_case__  ,     token_type_ids=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Tuple							    = model(snake_case__				)
       self.parent.assertEqual(result.pooler_output.shape  ,     (self.batch_size, self.projection_dim or self.hidden_size)				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = TFDPRQuestionEncoder(config=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = model(snake_case__  ,     attention_mask=snake_case__  ,     token_type_ids=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = model(snake_case__  ,     token_type_ids=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = model(snake_case__				)
       self.parent.assertEqual(result.pooler_output.shape  ,     (self.batch_size, self.projection_dim or self.hidden_size)				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = TFDPRReader(config=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Tuple							    = model(snake_case__  ,     attention_mask=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 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = self.prepare_config_and_inputs()
       (
           (
           _SCREAMING_SNAKE_CASE
       )    ,		(
           _SCREAMING_SNAKE_CASE
       )    ,		(
           _SCREAMING_SNAKE_CASE
       )    ,		(
           _SCREAMING_SNAKE_CASE
       )    ,		(
           _SCREAMING_SNAKE_CASE
       )    ,		(
           _SCREAMING_SNAKE_CASE
       )    ,		(
           _SCREAMING_SNAKE_CASE
       )    ,		
       )   :				Any							    = config_and_inputs
       _SCREAMING_SNAKE_CASE   :				str							    = {"input_ids": input_ids}
       return config, inputs_dict
@require_tf
class 			UpperCamelCase      (							__SCREAMING_SNAKE_CASE      ,       __SCREAMING_SNAKE_CASE      ,       unittest.TestCase  ):
     A__      =			(
         (
             TFDPRContextEncoder,
             TFDPRQuestionEncoder,
             TFDPRReader,
         )
         if is_tf_available()
         else ()
     )
     A__      =			{"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

     A__      =			False
     A__      =			False
     A__      =			False
     A__      =			False
     A__      =			False
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = TFDPRModelTester(self				)
       _SCREAMING_SNAKE_CASE   :				int							    = ConfigTester(self  ,     config_class=snake_case__  ,     hidden_size=37				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       self.config_tester.run_common_tests()
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Dict							    = self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_dpr_context_encoder(*snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_dpr_question_encoder(*snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_dpr_reader(*snake_case__				)




     @slow
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = TFDPRContextEncoder.from_pretrained(snake_case__				)
         self.assertIsNotNone(snake_case__				)

       for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = TFDPRContextEncoder.from_pretrained(snake_case__				)
         self.assertIsNotNone(snake_case__				)

       for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _SCREAMING_SNAKE_CASE   :				Any							    = TFDPRQuestionEncoder.from_pretrained(snake_case__				)
         self.assertIsNotNone(snake_case__				)

       for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _SCREAMING_SNAKE_CASE   :				Any							    = TFDPRReader.from_pretrained(snake_case__				)
         self.assertIsNotNone(snake_case__				)
@require_tf
class 			UpperCamelCase      (							unittest.TestCase  ):
     @slow
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Dict							    = TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base"				)

       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = tf.constant(
           [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]]				)  # [CLS] hello, is my dog cute? [SEP]
       _SCREAMING_SNAKE_CASE   :				Any							    = model(snake_case__				)[0]  # embedding shape = (1, 768)
       # compare the actual values for a slice.
       _SCREAMING_SNAKE_CASE   :				str							    = 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				)				)





"""simple docstring"""
from __future__ import annotations

import time
from collections.abc import Sequence
from random import randint

from matplotlib import pyplot as plt





def    _lowerCAmelCase    (     lowerCamelCase__							:							Sequence[float],						lowerCamelCase__							:							int,						lowerCamelCase__							:							int				)  ->    tuple[int | None, int | None, float]:
  if not arr:
    return None, None, 0
  if low == high:
    return low, high, arr[low]

  _SCREAMING_SNAKE_CASE   :				Any							    = (low + high) // 2
  _SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE   :				Optional[int]							    = max_subarray(lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__				)
  _SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE   :				List[str]							    = max_subarray(lowerCamelCase__,						mid + 1,						lowerCamelCase__				)
  _SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE   :				str							    = max_cross_sum(lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__,						lowerCamelCase__				)
  if left_sum >= right_sum and left_sum >= cross_sum:
    return left_low, left_high, left_sum
  elif right_sum >= left_sum and right_sum >= cross_sum:
    return right_low, right_high, right_sum
  return cross_left, cross_right, cross_sum





def    _lowerCAmelCase    (     lowerCamelCase__							:							Sequence[float],						lowerCamelCase__							:							int,						lowerCamelCase__							:							int,						lowerCamelCase__							:							int				)  ->    tuple[int, int, float]:
  _SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE   :				List[Any]							    = float("-inf"				), -1
  _SCREAMING_SNAKE_CASE    ,		_SCREAMING_SNAKE_CASE   :				Dict							    = float("-inf"				), -1

  _SCREAMING_SNAKE_CASE   :				int | float							    = 0
  for i in range(lowerCamelCase__,						low - 1,						-1				):
    summ += arr[i]
    if summ > left_sum:
      _SCREAMING_SNAKE_CASE   :				int							    = summ
      _SCREAMING_SNAKE_CASE   :				Tuple							    = i

  _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = 0
  for i in range(mid + 1,						high + 1				):
    summ += arr[i]
    if summ > right_sum:
      _SCREAMING_SNAKE_CASE   :				int							    = summ
      _SCREAMING_SNAKE_CASE   :				Any							    = i

  return max_left, max_right, (left_sum + right_sum)





def    _lowerCAmelCase    (     lowerCamelCase__							:							int				)  ->    float:
  _SCREAMING_SNAKE_CASE   :				Any							    = [randint(1,						lowerCamelCase__				) for _ in range(lowerCamelCase__				)]
  _SCREAMING_SNAKE_CASE   :				int							    = time.time()
  max_subarray(lowerCamelCase__,						0,						input_size - 1				)
  _SCREAMING_SNAKE_CASE   :				List[str]							    = time.time()
  return end - start





def    _lowerCAmelCase    (     )  ->    None:
  _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = [1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0]
  _SCREAMING_SNAKE_CASE   :				int							    = [time_max_subarray(lowerCamelCase__				) for input_size in input_sizes]
  print("No of Inputs\t\tTime Taken"				)
  for input_size, runtime in zip(lowerCamelCase__,						lowerCamelCase__				):
    print(lowerCamelCase__,						"\t\t",						lowerCamelCase__				)
  plt.plot(lowerCamelCase__,						lowerCamelCase__				)
  plt.xlabel("Number of Inputs"				)
  plt.ylabel("Time taken in seconds"				)
  plt.show()


if __name__ == "__main__":
      from doctest import testmod

      testmod()



