




'''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__         =     collections.namedtuple(
    '''CheckpointState''', ['''model_dict''', '''optimizer_dict''', '''scheduler_dict''', '''offset''', '''epoch''', '''encoder_params''']
)




def    snake_case__     (  a	)			->       CheckpointState:





			'''simple docstring'''






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





class __magic_name__:






						def __init__(   self						:						Tuple					,   __UpperCamelCase						:						Path       ):



									'''simple docstring'''






									snake_case__          =						src_file






						def       __lowerCAmelCase(   self						:						List[Any]       ):



									'''simple docstring'''






									raise NotImplementedError







						@staticmethod
						def       __lowerCAmelCase(   __UpperCamelCase						:						str					,   *__UpperCamelCase						:						Optional[int]					,   **__UpperCamelCase						:						int       ):



									'''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__(						__lowerCAmelCase      ):






						def       __lowerCAmelCase(   self						:						Tuple       ):



									'''simple docstring'''






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







class __magic_name__(						__lowerCAmelCase      ):






						def       __lowerCAmelCase(   self						:						Optional[Any]       ):



									'''simple docstring'''






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







class __magic_name__(						__lowerCAmelCase      ):






						def       __lowerCAmelCase(   self						:						str       ):



									'''simple docstring'''






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







def    snake_case__     (  a       ,      a       ,      a	)			->       int:





			'''simple docstring'''






			snake_case__          =						Path(a	)
			dest_dir.mkdir(exist_ok=a	)

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


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

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

# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from typing import List



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__						):
					'''simple docstring'''
					if name != "training_function" and name != "main":
										raise ValueError(f'Incorrect function name passed: {name}, choose either \'main\' or \'training_function\''						)
					lowercase      ,		lowercase		      =		[], False
					for line in lines:
										if not found_start and f'def {name}' in line:
															lowercase		      =		True
															good_lines.append(lowerCAmelCase__						)
															continue
										if found_start:
															if name == "training_function" and "def main" in line:
																				return good_lines
															if name == "main" and "if __name__" in line:
																				return good_lines
															good_lines.append(lowerCAmelCase__						)



def 			UpperCamelCase       (				lowerCAmelCase__						):
					'''simple docstring'''
					return [line for line in lines if not line.lstrip().startswith('''#'''						) and line != "\n"]



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = None						):
					'''simple docstring'''
					with open(lowerCAmelCase__					,     '''r'''						) as f:
										lowercase		      =		f.readlines()
					with open(os.path.abspath(os.path.join('''examples'''					,     '''nlp_example.py'''						)						)					,     '''r'''						) as f:
										lowercase		      =		f.readlines()
					with open(lowerCAmelCase__					,     '''r'''						) as f:
										lowercase		      =		f.readlines()
					if secondary_filename is not None:
										with open(lowerCAmelCase__					,     '''r'''						) as f:
															lowercase		      =		f.readlines()

    # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
					if parser_only:
										lowercase		      =		clean_lines(get_function_contents_by_name(lowerCAmelCase__					,     '''main'''						)						)
										lowercase		      =		clean_lines(get_function_contents_by_name(lowerCAmelCase__					,     '''main'''						)						)
										lowercase		      =		clean_lines(get_function_contents_by_name(lowerCAmelCase__					,     '''main'''						)						)
										if secondary_filename is not None:
															lowercase		      =		clean_lines(get_function_contents_by_name(lowerCAmelCase__					,     '''main'''						)						)
					else:
										lowercase		      =		clean_lines(get_function_contents_by_name(lowerCAmelCase__					,     '''training_function'''						)						)
										lowercase		      =		clean_lines(get_function_contents_by_name(lowerCAmelCase__					,     '''training_function'''						)						)
										lowercase		      =		clean_lines(get_function_contents_by_name(lowerCAmelCase__					,     '''training_function'''						)						)
										if secondary_filename is not None:
															lowercase		      =		clean_lines(
															    get_function_contents_by_name(lowerCAmelCase__					,     '''training_function'''						)						)

					lowercase		      =		'''train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n'''

					# Specific code in our script that differs from the full version, aka what is new
					lowercase		      =		[]
					lowercase		      =		[]  # We keep track of the idxs just in case it's a repeated statement
					lowercase		      =		iter(lowerCAmelCase__						)
					for i in range(len(lowerCAmelCase__						) - 1						):
										if i not in passed_idxs:
															lowercase		      =		next(lowerCAmelCase__						)
															if (line not in full_file_func) and (line.lstrip() != _dl_line):
																				if "TESTING_MOCKED_DATALOADERS" not in line:
																									new_feature_code.append(lowerCAmelCase__						)
																									passed_idxs.append(lowerCAmelCase__						)
																				else:
																									# Skip over the `config['num_epochs'] = 2` statement
																									lowercase		      =		next(lowerCAmelCase__						)

    # Extract out just the new parts from the full_file_training_func
					lowercase		      =		[]
					lowercase		      =		[]  # We keep track of the idxs just in case it's a repeated statement
					for i, line in enumerate(lowerCAmelCase__						):
										if i not in passed_idxs:
															if (line not in full_file_func) and (line.lstrip() != _dl_line):
																				if "TESTING_MOCKED_DATALOADERS" not in line:
																									new_full_example_parts.append(lowerCAmelCase__						)
																									passed_idxs.append(lowerCAmelCase__						)

    # Finally, get the overall diff
					lowercase		      =		[line for line in new_feature_code if line not in new_full_example_parts]
					if secondary_filename is not None:
										lowercase		      =		[line for line in full_file_contents if line not in secondary_file_func]
										lowercase		      =		[line for line in diff_from_example if line not in diff_from_two]

					return diff_from_example




