

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 			A						:







    """simple docstring"""





    def __init__(				self			:	Optional[int],lowercase_			:	List[Any],lowercase_			:	Union[str, Any]=1_3,lowercase_			:	List[Any]=7,lowercase_			:	Tuple=True,lowercase_			:	Tuple=True,lowercase_			:	Any=True,lowercase_			:	Dict=True,lowercase_			:	str=9_9,lowercase_			:	Dict=3_2,lowercase_			:	Union[str, Any]=2,lowercase_			:	List[Any]=4,lowercase_			:	List[Any]=3_7,lowercase_			:	Union[str, Any]="gelu",lowercase_			:	List[str]=0.1,lowercase_			:	Tuple=0.1,lowercase_			:	Optional[int]=5_1_2,lowercase_			:	Optional[int]=1_6,lowercase_			:	Dict=2,lowercase_			:	int=0.02,lowercase_			:	Optional[Any]=3,lowercase_			:	Union[str, Any]=4,lowercase_			:	Tuple=None,lowercase_			:	str=0,)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       parent
        A__   				=       batch_size
        A__   				=       seq_length
        A__   				=       is_training
        A__   				=       use_input_mask
        A__   				=       use_token_type_ids
        A__   				=       use_labels
        A__   				=       vocab_size
        A__   				=       hidden_size
        A__   				=       num_hidden_layers
        A__   				=       num_attention_heads
        A__   				=       intermediate_size
        A__   				=       hidden_act
        A__   				=       hidden_dropout_prob
        A__   				=       attention_probs_dropout_prob
        A__   				=       max_position_embeddings
        A__   				=       type_vocab_size
        A__   				=       type_sequence_label_size
        A__   				=       initializer_range
        A__   				=       num_labels
        A__   				=       num_choices
        A__   				=       scope
        A__   				=       projection_dim


    def 						snake_case__					(				self			:	Any		)->   str:





        '''simple docstring'''







        A__   				=       ids_tensor([self.batch_size, self.seq_length],self.vocab_size		)

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

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

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

        A__   				=       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,)
        A__   				=       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			:	str,lowercase_			:	List[str],lowercase_			:	int,lowercase_			:	Union[str, Any],lowercase_			:	List[Any],lowercase_			:	Dict,lowercase_			:	str,lowercase_			:	List[Any]		)->   Tuple:





        '''simple docstring'''







        A__   				=       TFDPRContextEncoder(config=lowercase_		)
        A__   				=       model(lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_		)
        A__   				=       model(lowercase_,token_type_ids=lowercase_		)
        A__   				=       model(lowercase_		)
        self.parent.assertEqual(result.pooler_output.shape,(self.batch_size, self.projection_dim or self.hidden_size)		)


    def 						snake_case__					(				self			:	Tuple,lowercase_			:	Optional[Any],lowercase_			:	List[str],lowercase_			:	List[str],lowercase_			:	Tuple,lowercase_			:	Optional[int],lowercase_			:	Any,lowercase_			:	Optional[int]		)->   Tuple:





        '''simple docstring'''







        A__   				=       TFDPRQuestionEncoder(config=lowercase_		)
        A__   				=       model(lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_		)
        A__   				=       model(lowercase_,token_type_ids=lowercase_		)
        A__   				=       model(lowercase_		)
        self.parent.assertEqual(result.pooler_output.shape,(self.batch_size, self.projection_dim or self.hidden_size)		)


    def 						snake_case__					(				self			:	Union[str, Any],lowercase_			:	List[str],lowercase_			:	Any,lowercase_			:	int,lowercase_			:	int,lowercase_			:	Tuple,lowercase_			:	List[str],lowercase_			:	Optional[Any]		)->   List[str]:





        '''simple docstring'''







        A__   				=       TFDPRReader(config=lowercase_		)
        A__   				=       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			:	str		)->   Union[str, Any]:





        '''simple docstring'''







        A__   				=       self.prepare_config_and_inputs()
        (
            A__  
        )   				=       config_and_inputs
        A__   				=       {"input_ids": input_ids}
        return config, inputs_dict




@require_tf
class 			A						(							lowerCamelCase__   ,							lowerCamelCase__   ,							unittest.TestCase			):







    """simple docstring"""





    lowerCamelCase		     =							(
        (
            TFDPRContextEncoder,
            TFDPRQuestionEncoder,
            TFDPRReader,
        )
        if is_tf_available()
        else ()
    )
    lowerCamelCase		     =							{'feature-extraction': TFDPRQuestionEncoder} if is_tf_available() else {}

    lowerCamelCase		     =							False
    lowerCamelCase		     =							False
    lowerCamelCase		     =							False
    lowerCamelCase		     =							False
    lowerCamelCase		     =							False


    def 						snake_case__					(				self			:	Optional[int]		)->   List[Any]:





        '''simple docstring'''







        A__   				=       TFDPRModelTester(self		)
        A__   				=       ConfigTester(self,config_class=lowercase_,hidden_size=3_7		)


    def 						snake_case__					(				self			:	Optional[Any]		)->   Union[str, Any]:





        '''simple docstring'''







        self.config_tester.run_common_tests()


    def 						snake_case__					(				self			:	List[str]		)->   int:





        '''simple docstring'''







        A__   				=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_dpr_context_encoder(*lowercase_		)


    def 						snake_case__					(				self			:	int		)->   List[Any]:





        '''simple docstring'''







        A__   				=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_dpr_question_encoder(*lowercase_		)


    def 						snake_case__					(				self			:	List[Any]		)->   Optional[int]:





        '''simple docstring'''







        A__   				=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_dpr_reader(*lowercase_		)


    @slow
    def 						snake_case__					(				self			:	Union[str, Any]		)->   List[str]:





        '''simple docstring'''







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

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

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

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




@require_tf
class 			A						(							unittest.TestCase			):







    """simple docstring"""





    @slow
    def 						snake_case__					(				self			:	Optional[Any]		)->   List[str]:





        '''simple docstring'''







        A__   				=       TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'		)

        A__   				=       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]
        A__   				=       model(lowercase_		)[0]  # embedding shape = (1, 768)
        # compare the actual values for a slice.
        A__   				=       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		)		)








def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     list[list[int]]				)							->				int:





    '''simple docstring'''






    def update_area_of_max_square(SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     int				) -> int:
        # BASE CASE
        if row >= rows or col >= cols:
            return 0

        A__   				=       update_area_of_max_square(SCREAMING_SNAKE_CASE__   ,      col + 1				)
        A__   				=       update_area_of_max_square(row + 1   ,      col + 1				)
        A__   				=       update_area_of_max_square(row + 1   ,      SCREAMING_SNAKE_CASE__				)

        if mat[row][col]:
            A__   				=       1 + min([right, diagonal, down]				)
            A__   				=       max(largest_square_area[0]   ,      SCREAMING_SNAKE_CASE__				)
            return sub_problem_sol
        else:
            return 0

    A__   				=       [0]
    update_area_of_max_square(0   ,      0				)
    return largest_square_area[0]
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     list[list[int]]				)							->				int:





    '''simple docstring'''






    def update_area_of_max_square_using_dp_array(
        SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     list[list[int]]				) -> int:
        if row >= rows or col >= cols:
            return 0
        if dp_array[row][col] != -1:
            return dp_array[row][col]

        A__   				=       update_area_of_max_square_using_dp_array(SCREAMING_SNAKE_CASE__   ,      col + 1   ,      SCREAMING_SNAKE_CASE__				)
        A__   				=       update_area_of_max_square_using_dp_array(row + 1   ,      col + 1   ,      SCREAMING_SNAKE_CASE__				)
        A__   				=       update_area_of_max_square_using_dp_array(row + 1   ,      SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)

        if mat[row][col]:
            A__   				=       1 + min([right, diagonal, down]				)
            A__   				=       max(largest_square_area[0]   ,      SCREAMING_SNAKE_CASE__				)
            A__   				=       sub_problem_sol
            return sub_problem_sol
        else:
            return 0

    A__   				=       [0]
    A__   				=       [[-1] * cols for _ in range(SCREAMING_SNAKE_CASE__				)]
    update_area_of_max_square_using_dp_array(0   ,      0   ,      SCREAMING_SNAKE_CASE__				)

    return largest_square_area[0]
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     list[list[int]]				)							->				int:





    '''simple docstring'''






    A__   				=       [[0] * (cols + 1) for _ in range(rows + 1				)]
    A__   				=       0
    for row in range(rows - 1   ,      -1   ,      -1				):
        for col in range(cols - 1   ,      -1   ,      -1				):
            A__   				=       dp_array[row][col + 1]
            A__   				=       dp_array[row + 1][col + 1]
            A__   				=       dp_array[row + 1][col]

            if mat[row][col] == 1:
                A__   				=       1 + min(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)
                A__   				=       max(dp_array[row][col]   ,      SCREAMING_SNAKE_CASE__				)
            else:
                A__   				=       0

    return largest_square_area
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     list[list[int]]				)							->				int:





    '''simple docstring'''






    A__   				=       [0] * (cols + 1)
    A__   				=       [0] * (cols + 1)
    A__   				=       0
    for row in range(rows - 1   ,      -1   ,      -1				):
        for col in range(cols - 1   ,      -1   ,      -1				):
            A__   				=       current_row[col + 1]
            A__   				=       next_row[col + 1]
            A__   				=       next_row[col]

            if mat[row][col] == 1:
                A__   				=       1 + min(SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__   ,      SCREAMING_SNAKE_CASE__				)
                A__   				=       max(current_row[col]   ,      SCREAMING_SNAKE_CASE__				)
            else:
                A__   				=       0
        A__   				=       current_row

    return largest_square_area


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))

