
'''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 ,       lowercase_ ,       lowercase_=13 ,       lowercase_=7 ,       lowercase_=True ,       lowercase_=True ,       lowercase_=True ,       lowercase_=True ,       lowercase_=99 ,       lowercase_=32 ,       lowercase_=2 ,       lowercase_=4 ,       lowercase_=37 ,       lowercase_="gelu" ,       lowercase_=0.1 ,       lowercase_=0.1 ,       lowercase_=5_12 ,       lowercase_=16 ,       lowercase_=2 ,       lowercase_=0.02 ,       lowercase_=3 ,       lowercase_=4 ,       lowercase_=None ,       lowercase_=0 ,       ):
     snake_case_ :    Optional[Any]     			=						parent
     snake_case_ :    Any     			=						batch_size
     snake_case_ :    Optional[int]     			=						seq_length
     snake_case_ :    Any     			=						is_training
     snake_case_ :    Any     			=						use_input_mask
     snake_case_ :    Union[str, Any]     			=						use_token_type_ids
     snake_case_ :    Dict     			=						use_labels
     snake_case_ :    List[Any]     			=						vocab_size
     snake_case_ :    Union[str, Any]     			=						hidden_size
     snake_case_ :    Optional[Any]     			=						num_hidden_layers
     snake_case_ :    Tuple     			=						num_attention_heads
     snake_case_ :    Dict     			=						intermediate_size
     snake_case_ :    Tuple     			=						hidden_act
     snake_case_ :    List[Any]     			=						hidden_dropout_prob
     snake_case_ :    List[Any]     			=						attention_probs_dropout_prob
     snake_case_ :    List[Any]     			=						max_position_embeddings
     snake_case_ :    Union[str, Any]     			=						type_vocab_size
     snake_case_ :    Any     			=						type_sequence_label_size
     snake_case_ :    str     			=						initializer_range
     snake_case_ :    List[str]     			=						num_labels
     snake_case_ :    List[str]     			=						num_choices
     snake_case_ :    List[Any]     			=						scope
     snake_case_ :    int     			=						projection_dim





 def        snake_case__		(    self):
     snake_case_ :    Any     			=						ids_tensor([self.batch_size, self.seq_length] ,       self.vocab_size)

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

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

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

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





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_):
     snake_case_ :    Dict     			=						TFDPRQuestionEncoder(config=lowercase_)
     snake_case_ :    Optional[int]     			=						model(lowercase_ ,       attention_mask=lowercase_ ,       token_type_ids=lowercase_)
     snake_case_ :    Optional[int]     			=						model(lowercase_ ,       token_type_ids=lowercase_)
     snake_case_ :    List[str]     			=						model(lowercase_)
     self.parent.assertEqual(result.pooler_output.shape ,       (self.batch_size, self.projection_dim or self.hidden_size))





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_):
     snake_case_ :    Optional[int]     			=						TFDPRReader(config=lowercase_)
     snake_case_ :    Any     			=						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        snake_case__		(    self):
     snake_case_ :    Optional[Any]     			=						self.prepare_config_and_inputs()
     (
         (
         snake_case_
     )			, (
         snake_case_
     )			, (
         snake_case_
     )			, (
         snake_case_
     )			, (
         snake_case_
     )			, (
         snake_case_
     )			, (
         snake_case_
     )			, 
     ) :    Tuple     			=						config_and_inputs
     snake_case_ :    Union[str, Any]     			=						{"input_ids": input_ids}
     return config, inputs_dict






@require_tf
class    UpperCAmelCase_				(	snake_case__    ,						snake_case__    ,						unittest.TestCase					):
 UpperCAmelCase_		    =						(
     (
         TFDPRContextEncoder,
         TFDPRQuestionEncoder,
         TFDPRReader,
     )
     if is_tf_available()
     else ()
 )
 UpperCAmelCase_		    =						{"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False





 def        snake_case__		(    self):
     snake_case_ :    Any     			=						TFDPRModelTester(self)
     snake_case_ :    Tuple     			=						ConfigTester(self ,       config_class=lowercase_ ,       hidden_size=37)





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





 def        snake_case__		(    self):
     snake_case_ :    int     			=						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_context_encoder(*lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    Tuple     			=						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_question_encoder(*lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    int     			=						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_reader(*lowercase_)





 @slow
 def        snake_case__		(    self):
     for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_ :    List[Any]     			=						TFDPRContextEncoder.from_pretrained(lowercase_)
         self.assertIsNotNone(lowercase_)

     for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_ :    List[str]     			=						TFDPRContextEncoder.from_pretrained(lowercase_)
         self.assertIsNotNone(lowercase_)

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

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






@require_tf
class    UpperCAmelCase_				(	unittest.TestCase					):





 @slow
 def        snake_case__		(    self):
     snake_case_ :    Any     			=						TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")

     snake_case_ :    Dict     			=						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]
     snake_case_ :    List[Any]     			=						model(lowercase_)[0]  # embedding shape = (1, 768)
     # compare the actual values for a slice.
     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'''
import doctest
from collections import deque

import numpy as np






class    UpperCAmelCase_				:





 def __init__(    self):
     snake_case_ :    List[Any]     			=						[2, 1, 2, -1]
     snake_case_ :    int     			=						[1, 2, 3, 4]





 def        snake_case__		(    self):
     snake_case_ :    str     			=						len(self.first_signal)
     snake_case_ :    Any     			=						len(self.second_signal)

     snake_case_ :    List[Any]     			=						max(lowercase_ ,       lowercase_)

     # create a zero matrix of max_length x max_length
     snake_case_ :    Dict     			=						[[0] * max_length for i in range(lowercase_)]

     # fills the smaller signal with zeros to make both signals of same length
     if length_first_signal < length_second_signal:
         self.first_signal += [0] * (max_length - length_first_signal)
     elif length_first_signal > length_second_signal:
         self.second_signal += [0] * (max_length - length_second_signal)
     for i in range(lowercase_):
         snake_case_ :    List[str]     			=						deque(self.second_signal)
         rotated_signal.rotate(lowercase_)
         for j, item in enumerate(lowercase_):
             matrix[i][j] += item

        # multiply the matrix with the first signal
     snake_case_ :    Any     			=						np.matmul(np.transpose(lowercase_) ,       np.transpose(self.first_signal))

     # rounding-off to two decimal places
     return [round(lowercase_ ,       2) for i in final_signal]


if __name__ == "__main__":
  doctest.testmod()




