

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


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




def      UpperCAmelCase__							(     _A :					str				):





  '''simple docstring'''







  print(F"""Reading saved model from {model_file}"""				)
  a__    =torch.load(__UpperCamelCase      , map_location=lambda _A      , _A				: default_restore_location(__UpperCamelCase      , '''cpu'''				)				)
  return CheckpointState(**__UpperCamelCase				)







class 		__magic_name__     :

   '''simple docstring'''




   def __init__(							self,       lowercase_			)				->       List[Any]:






     """simple docstring"""






     a__    =src_file



   def 					_UpperCAmelCase					(							self			)				->       str:






     """simple docstring"""






     raise NotImplementedError



   @staticmethod
   def 					_UpperCAmelCase					(							lowercase_,       *lowercase_,       **lowercase_			)				->       "DPRState":






     """simple docstring"""






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







class 		__magic_name__     (				__a				):

   '''simple docstring'''




   def 					_UpperCAmelCase					(							self			)				->       List[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(UpperCamelCase__			):
         a__    =key[len(UpperCamelCase__			) :]
         if not key.startswith('''encode_proj.'''			):
           a__    ='''bert_model.''' + key
         a__    =value
     encoder.load_state_dict(UpperCamelCase__			)
     return model







class 		__magic_name__     (				__a				):

   '''simple docstring'''




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






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







class 		__magic_name__     (				__a				):

   '''simple docstring'''




   def 					_UpperCAmelCase					(							self			)				->       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(UpperCamelCase__			)
     return model





def      UpperCAmelCase__							(     _A :					str      , _A :					Path      , _A :					Path				):





  '''simple docstring'''







  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__":
       lowerCamelCase 	=   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.''')
       lowerCamelCase 	=   parser.parse_args()

       lowerCamelCase 	=   Path(args.src)
       lowerCamelCase 	=   f"""converted-{src_file.name}""" if args.dest is None else args.dest
       lowerCamelCase 	=   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"""

def    lowerCAmelCase			(__UpperCamelCase							:    int							,					__UpperCamelCase							:    int			):
							"""simple docstring"""


							return (input_a, input_a).count(0			) % 2


def    lowerCAmelCase			():
							"""simple docstring"""


							assert xor_gate(0							,					0			) == 0
							assert xor_gate(0							,					1			) == 1
							assert xor_gate(1							,					0			) == 1
							assert xor_gate(1							,					1			) == 0


if __name__ == "__main__":
				print(xor_gate(0, 0))
				print(xor_gate(0, 1))



