

"""simple docstring"""



import argparse
import collections
from pathlib import Path

import torch
from torch.serialization import default_restore_location

from transformers import BertConfig, DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader


SCREAMING_SNAKE_CASE_       :						List[Any]					=    collections.namedtuple(
    'CheckpointState', ['model_dict', 'optimizer_dict', 'scheduler_dict', 'offset', 'epoch', 'encoder_params']
)





def 			_snake_case  (     UpperCAmelCase_	:       int      ):
     print(F"""Reading saved model from {model_file}"""      )
     A__				      =	torch.load(UpperCAmelCase_       , map_location=lambda UpperCAmelCase_       , UpperCAmelCase_      : default_restore_location(UpperCAmelCase_       , """cpu"""      )      )
     return CheckpointState(**UpperCAmelCase_      )



class        a    :



    """simple docstring"""



    def __init__(  self:			int     ,    UpperCamelCase:			str							):






         """simple docstring"""


         A__				      =	src_file

    def 					UpperCamelCase						(  self:			str							):






         """simple docstring"""


         raise NotImplementedError





    @staticmethod
    def 					UpperCamelCase						(  UpperCamelCase:			Any     ,    *UpperCamelCase:			Any     ,    **UpperCamelCase:			Tuple							):






         """simple docstring"""


         if comp_type.startswith("""c"""							):
              return DPRContextEncoderState(*__lowercase     ,    **__lowercase							)
         if comp_type.startswith("""q"""							):
              return DPRQuestionEncoderState(*__lowercase     ,    **__lowercase							)
         if comp_type.startswith("""r"""							):
              return DPRReaderState(*__lowercase     ,    **__lowercase							)
         else:
              raise ValueError("""Component type must be either \'ctx_encoder\', \'question_encoder\' or \'reader\'."""							)



class        a    (							_lowerCamelCase					):



    """simple docstring"""



    def 					UpperCamelCase						(  self:			Tuple							):






         """simple docstring"""


         A__				      =	DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict("""bert-base-uncased"""							)[0]							)							)
         print(f"""Loading DPR biencoder from {self.src_file}"""							)
         A__				      =	load_states_from_checkpoint(self.src_file							)
         A__				      =	model.ctx_encoder, 'ctx_model.'
         # Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
         A__				      =	{'bert_model.embeddings.position_ids': model.ctx_encoder.bert_model.embeddings.position_ids}
         for key, value in saved_state.model_dict.items():
              if key.startswith(__lowercase							):
                   A__				      =	key[len(__lowercase							) :]
                   if not key.startswith("""encode_proj."""							):
                        A__				      =	'bert_model.' + key
                   A__				      =	value
         encoder.load_state_dict(__lowercase							)
         return model



class        a    (							_lowerCamelCase					):



    """simple docstring"""



    def 					UpperCamelCase						(  self:			Any							):






         """simple docstring"""


         A__				      =	DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict("""bert-base-uncased"""							)[0]							)							)
         print(f"""Loading DPR biencoder from {self.src_file}"""							)
         A__				      =	load_states_from_checkpoint(self.src_file							)
         A__				      =	model.question_encoder, 'question_model.'
         # Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
         A__				      =	{'bert_model.embeddings.position_ids': model.question_encoder.bert_model.embeddings.position_ids}
         for key, value in saved_state.model_dict.items():
              if key.startswith(__lowercase							):
                   A__				      =	key[len(__lowercase							) :]
                   if not key.startswith("""encode_proj."""							):
                        A__				      =	'bert_model.' + key
                   A__				      =	value
         encoder.load_state_dict(__lowercase							)
         return model



class        a    (							_lowerCamelCase					):



    """simple docstring"""



    def 					UpperCamelCase						(  self:			Optional[Any]							):






         """simple docstring"""


         A__				      =	DPRReader(DPRConfig(**BertConfig.get_config_dict("""bert-base-uncased"""							)[0]							)							)
         print(f"""Loading DPR reader from {self.src_file}"""							)
         A__				      =	load_states_from_checkpoint(self.src_file							)
         # Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
         A__				      =	{
             'encoder.bert_model.embeddings.position_ids': model.span_predictor.encoder.bert_model.embeddings.position_ids
         }
         for key, value in saved_state.model_dict.items():
              if key.startswith("""encoder."""							) and not key.startswith("""encoder.encode_proj"""							):
                   A__				      =	'encoder.bert_model.' + key[len("""encoder."""							) :]
              A__				      =	value
         model.span_predictor.load_state_dict(__lowercase							)
         return model





def 			_snake_case  (     UpperCAmelCase_	:       List[str]       , UpperCAmelCase_	:       Union[str, Any]       , UpperCAmelCase_	:       str      ):
     A__				      =	Path(UpperCAmelCase_      )
     dest_dir.mkdir(exist_ok=UpperCAmelCase_      )

     A__				      =	DPRState.from_type(UpperCAmelCase_       , src_file=UpperCAmelCase_      )
     A__				      =	dpr_state.load_dpr_model()
     model.save_pretrained(UpperCAmelCase_      )
     model.from_pretrained(UpperCAmelCase_      )  # sanity check


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE_       :						str					=    argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '--type', type=str, help='Type of the component to convert: \'ctx_encoder\', \'question_encoder\' or \'reader\'.'
 )
 parser.add_argument(
     '--src',
     type=str,
     help=(
         'Path to the dpr checkpoint file. They can be downloaded from the official DPR repo'
         ' https://github.com/facebookresearch/DPR. Note that in the official repo, both encoders are stored in the'
         ' \'retriever\' checkpoints.'
     ),
 )
 parser.add_argument('--dest', type=str, default=None, help='Path to the output PyTorch model directory.')
 SCREAMING_SNAKE_CASE_       :						Union[str, Any]					=    parser.parse_args()

 SCREAMING_SNAKE_CASE_       :						Union[str, Any]					=    Path(args.src)
 SCREAMING_SNAKE_CASE_       :						Dict					=    f"""converted-{src_file.name}""" if args.dest is None else args.dest
 SCREAMING_SNAKE_CASE_       :						Optional[Any]					=    Path(dest_dir)
 assert src_file.exists()
 assert (
     args.type is not None
 ), "Please specify the component type of the DPR model to convert: 'ctx_encoder', 'question_encoder' or 'reader'."
 convert(args.type, src_file, dest_dir)












UpperCamelCase__						=		[
    [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
]






def    snake_case   (				A		,  A		,  A		,  A     )				->				bool:




	'''simple docstring'''


	return 0 <= row < rows and 0 <= col < cols






def    snake_case   (				A		,  A		,  A		,  A     )				->				int:




	'''simple docstring'''


	lowerCamelCase_				:						List[str]				  =				len(A     )
	lowerCamelCase_				:						Any				  =				len(mat[0]     )
	if is_safe(A		,  A		,  A		,  A     ) and (row, col) not in seen and mat[row][col] == 1:
		seen.add((row, col)     )
		return (
		    1
		    + depth_first_search(row + 1		,  A		,  A		,  A     )
		    + depth_first_search(row - 1		,  A		,  A		,  A     )
		    + depth_first_search(A		,  col + 1		,  A		,  A     )
		    + depth_first_search(A		,  col - 1		,  A		,  A     )
		)
	else:
		return 0






def    snake_case   (				A     )				->				int:




	'''simple docstring'''


	lowerCamelCase_				:						set				  =				set()

	lowerCamelCase_				:						Optional[Any]				  =				0
	for row, line in enumerate(A     ):
		for col, item in enumerate(A     ):
			if item == 1 and (row, col) not in seen:
				# Maximizing the area
				lowerCamelCase_				:						Optional[Any]				  =				max(A		,  depth_first_search(A		,  A		,  A		,  A     )     )
	return max_area


if __name__ == "__main__":
							import doctest

							print(find_max_area(matrix))  # Output -> 6
							doctest.testmod()
