
"""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


a		:					Dict    	=					collections.namedtuple(
    'CheckpointState', ['model_dict', 'optimizer_dict', 'scheduler_dict', 'offset', 'epoch', 'encoder_params']
)



def 						__magic_name__		(				UpperCamelCase    :		str    )    ->	CheckpointState:
    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 						lowercase:



     def __init__(       self    ,							__SCREAMING_SNAKE_CASE      )		->    Tuple:







         """simple docstring"""



         a__    = src_file



     def  lowercase__     (       self      )		->    Tuple:







         """simple docstring"""



         raise NotImplementedError




     @staticmethod
     def  lowercase__     (       __SCREAMING_SNAKE_CASE    ,							*__SCREAMING_SNAKE_CASE    ,							**__SCREAMING_SNAKE_CASE      )		->    "DPRState":







         """simple docstring"""



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







class 						lowercase(_lowercase					):



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







         """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__  ,    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(__SCREAMING_SNAKE_CASE      ):
                 a__    = key[len(__SCREAMING_SNAKE_CASE      ) :]
                 if not key.startswith('encode_proj.'      ):
                     a__    = 'bert_model.' + key
                 a__    = value
         encoder.load_state_dict(__SCREAMING_SNAKE_CASE      )
         return model







class 						lowercase(_lowercase					):



     def  lowercase__     (       self      )		->    str:







         """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__  ,    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(__SCREAMING_SNAKE_CASE      ):
                 a__    = key[len(__SCREAMING_SNAKE_CASE      ) :]
                 if not key.startswith('encode_proj.'      ):
                     a__    = 'bert_model.' + key
                 a__    = value
         encoder.load_state_dict(__SCREAMING_SNAKE_CASE      )
         return model







class 						lowercase(_lowercase					):



     def  lowercase__     (       self      )		->    Optional[int]:







         """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(__SCREAMING_SNAKE_CASE      )
         return model




def 						__magic_name__		(				UpperCamelCase    :		str       ,		UpperCamelCase    :		Path       ,		UpperCamelCase    :		Path    )    ->	int:
    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__":
    a		:					Optional[Any]    	=					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.')
    a		:					List[Any]    	=					parser.parse_args()

    a		:					Tuple    	=					Path(args.src)
    a		:					List[Any]    	=					F'''converted-{src_file.name}''' if args.dest is None else args.dest
    a		:					Dict    	=					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)




"""simple docstring"""




import math







class 						lowercase:



     def __init__(       self    ,							__SCREAMING_SNAKE_CASE      )		->    Optional[int]:







         """simple docstring"""



         a__    = len(__SCREAMING_SNAKE_CASE      )
         a__    = [0] * (
             4 * self.N
         )  # approximate the overall size of segment tree with array N
         self.build(1    ,							0    ,							self.N - 1      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE      )		->    Optional[Any]:







         """simple docstring"""



         return idx * 2



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE      )		->    Optional[int]:







         """simple docstring"""



         return idx * 2 + 1



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    List[str]:  # noqa: E741







         """simple docstring"""



         if l == r:
             a__    = A[l]
         else:
             a__    = (l + r) // 2
             self.build(self.left(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
             self.build(self.right(__SCREAMING_SNAKE_CASE      )    ,							mid + 1    ,							__SCREAMING_SNAKE_CASE      )
             a__    = max(self.st[self.left(__SCREAMING_SNAKE_CASE      )]    ,							self.st[self.right(__SCREAMING_SNAKE_CASE      )]      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    int:







         """simple docstring"""



         return self.update_recursive(1    ,							0    ,							self.N - 1    ,							a - 1    ,							b - 1    ,							__SCREAMING_SNAKE_CASE      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    Optional[int]:  # noqa: E741







         """simple docstring"""



         if r < a or l > b:
             return True
         if l == r:
             a__    = val
             return True
         a__    = (l + r) // 2
         self.update_recursive(self.left(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         self.update_recursive(self.right(__SCREAMING_SNAKE_CASE      )    ,							mid + 1    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         a__    = max(self.st[self.left(__SCREAMING_SNAKE_CASE      )]    ,							self.st[self.right(__SCREAMING_SNAKE_CASE      )]      )
         return True



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    List[str]:







         """simple docstring"""



         return self.query_recursive(1    ,							0    ,							self.N - 1    ,							a - 1    ,							b - 1      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )		->    Any:  # noqa: E741







         """simple docstring"""



         if r < a or l > b:
             return -math.inf
         if l >= a and r <= b:
             return self.st[idx]
         a__    = (l + r) // 2
         a__    = self.query_recursive(self.left(__SCREAMING_SNAKE_CASE      )    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         a__    = self.query_recursive(self.right(__SCREAMING_SNAKE_CASE      )    ,							mid + 1    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         return max(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )




     def  lowercase__     (       self      )		->    List[Any]:







         """simple docstring"""



         a__    = []
         for i in range(1    ,							N + 1      ):
             show_list += [self.query(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )]
         print(__SCREAMING_SNAKE_CASE      )


if __name__ == "__main__":
    a		:					Union[str, Any]    	=					[1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
    a		:					Dict    	=					15
    a		:					Tuple    	=					SegmentTree(A)
    print(segt.query(4, 6))
    print(segt.query(7, 11))
    print(segt.query(7, 12))
    segt.update(1, 3, 1_11)
    print(segt.query(1, 15))
    segt.update(7, 8, 2_35)
    segt.show_data()


