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


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


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


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






class 		_lowercase :



						"""simple docstring"""




						def __init__(				self							:    List[str]     , UpperCamelCase__							:    Path				)				->				List[Any]:
													'''simple docstring'''



													__UpperCamelCase							=src_file





						def   UpperCAmelCase_ (				self							:    str				)				->				str:
													'''simple docstring'''



													raise NotImplementedError





						@staticmethod
						def   UpperCAmelCase_ (				UpperCamelCase__							:    str     , *UpperCamelCase__							:    List[str]     , **UpperCamelCase__							:    Dict				)				->				"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 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    List[str]				)				->				List[Any]:
													'''simple docstring'''



													__UpperCamelCase							=DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict('''bert-base-uncased'''				)[0]				)				)
													print(f"""Loading DPR biencoder from {self.src_file}"""				)
													__UpperCamelCase							=load_states_from_checkpoint(self.src_file				)
													__UpperCamelCase	,      __UpperCamelCase							=model.ctx_encoder, '''ctx_model.'''
													# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
													__UpperCamelCase							={'''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__				):
																											__UpperCamelCase							=key[len(UpperCamelCase__				) :]
																											if not key.startswith('''encode_proj.'''				):
																																		__UpperCamelCase							='''bert_model.''' + key
																											__UpperCamelCase							=value
													encoder.load_state_dict(UpperCamelCase__				)
													return model






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    int				)				->				Optional[int]:
													'''simple docstring'''



													__UpperCamelCase							=DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict('''bert-base-uncased'''				)[0]				)				)
													print(f"""Loading DPR biencoder from {self.src_file}"""				)
													__UpperCamelCase							=load_states_from_checkpoint(self.src_file				)
													__UpperCamelCase	,      __UpperCamelCase							=model.question_encoder, '''question_model.'''
													# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
													__UpperCamelCase							={'''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__				):
																											__UpperCamelCase							=key[len(UpperCamelCase__				) :]
																											if not key.startswith('''encode_proj.'''				):
																																		__UpperCamelCase							='''bert_model.''' + key
																											__UpperCamelCase							=value
													encoder.load_state_dict(UpperCamelCase__				)
													return model






class 		_lowercase (						__a      ):



						"""simple docstring"""




						def   UpperCAmelCase_ (				self							:    Optional[Any]				)				->				int:
													'''simple docstring'''



													__UpperCamelCase							=DPRReader(DPRConfig(**BertConfig.get_config_dict('''bert-base-uncased'''				)[0]				)				)
													print(f"""Loading DPR reader from {self.src_file}"""				)
													__UpperCamelCase							=load_states_from_checkpoint(self.src_file				)
													# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
													__UpperCamelCase							={
													    '''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'''				):
																											__UpperCamelCase							='''encoder.bert_model.''' + key[len('''encoder.'''				) :]
																				__UpperCamelCase							=value
													model.span_predictor.load_state_dict(UpperCamelCase__				)
													return model






def    lowerCAmelCase			(__UpperCamelCase							:    str							,					__UpperCamelCase							:    Path							,					__UpperCamelCase							:    Path			):
							"""simple docstring"""


							__UpperCamelCase							=Path(__UpperCamelCase			)
							dest_dir.mkdir(exist_ok=__UpperCamelCase			)

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


if __name__ == "__main__":
				__lowercase    =				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.''')
				__lowercase    =				parser.parse_args()

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



