




'''simple docstring'''







import argparse

import torch
from saprl.hub import distilhubert

from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
A			   =logging.get_logger(__name__)

A			   ={
    'post_extract_proj': 'feature_projection.projection',
    'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
    'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
    'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
    'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
    'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
    'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
    'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
    'fc2': 'encoder.layers.*.feed_forward.output_dense',
    'final_layer_norm': 'encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'encoder.layer_norm',
    'mask_emb': 'masked_spec_embed',
}





def 						snake_case_							(_a     :							Dict   ,       _a     :							Any   ,       _a     :							Dict   ,       _a     :							int   ,       _a     :							Any					):
    for attribute in key.split('''.'''					):
        UpperCAmelCase      	=		getattr(_a   ,       _a					)

    if weight_type is not None:
        UpperCAmelCase      	=		getattr(_a   ,       _a					).shape
    else:
        UpperCAmelCase      	=		hf_pointer.shape

    assert hf_shape == value.shape, (
        F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
        F" {value.shape} for {full_name}"
    )

    if weight_type == "weight":
        UpperCAmelCase      	=		value
    elif weight_type == "weight_g":
        UpperCAmelCase      	=		value
    elif weight_type == "weight_v":
        UpperCAmelCase      	=		value
    elif weight_type == "bias":
        UpperCAmelCase      	=		value
    else:
        UpperCAmelCase      	=		value

    logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}."					)





def 						snake_case_							(_a     :							Union[str, Any]   ,       _a     :							str					):
    UpperCAmelCase      	=		[]
    UpperCAmelCase      	=		fairseq_model.state_dict()

    UpperCAmelCase      	=		hf_model.feature_extractor

    for name, value in fairseq_dict.items():
        UpperCAmelCase      	=		False
        if "conv_layers" in name:
            load_conv_layer(
                _a   ,       _a   ,       _a   ,       _a   ,       hf_model.config.feat_extract_norm == '''group'''   ,       )
            UpperCAmelCase      	=		True
        else:
            for key, mapped_key in MAPPING.items():
                UpperCAmelCase      	=		mapped_key

                if key in name:
                    UpperCAmelCase      	=		True
                    if "*" in mapped_key:
                        UpperCAmelCase      	=		name.split(_a					)[0].split('''.'''					)[-2]
                        UpperCAmelCase      	=		mapped_key.replace('''*'''   ,       _a					)
                    if "weight_g" in name:
                        UpperCAmelCase      	=		"""weight_g"""
                    elif "weight_v" in name:
                        UpperCAmelCase      	=		"""weight_v"""
                    elif "weight" in name:
                        UpperCAmelCase      	=		"""weight"""
                    elif "bias" in name:
                        UpperCAmelCase      	=		"""bias"""
                    else:
                        UpperCAmelCase      	=		None
                    set_recursively(_a   ,       _a   ,       _a   ,       _a   ,       _a					)
                continue
        if not is_used:
            unused_weights.append(_a					)

    logger.warning(F"Unused weights: {unused_weights}"					)





def 						snake_case_							(_a     :							Any   ,       _a     :							List[str]   ,       _a     :							Tuple   ,       _a     :							Union[str, Any]   ,       _a     :							Optional[Any]					):
    UpperCAmelCase      	=		full_name.split('''conv_layers.'''					)[-1]
    UpperCAmelCase      	=		name.split('''.'''					)
    UpperCAmelCase      	=		int(items[0]					)
    UpperCAmelCase      	=		int(items[1]					)

    if type_id == 0:
        if "bias" in name:
            assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                F"{full_name} has size {value.shape}, but"
                F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
            )
            UpperCAmelCase      	=		value
            logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}."					)
        elif "weight" in name:
            assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                F"{full_name} has size {value.shape}, but"
                F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
            )
            UpperCAmelCase      	=		value
            logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}."					)
    elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
        if "bias" in name:
            assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
                " found."
            )
            UpperCAmelCase      	=		value
            logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."					)
        elif "weight" in name:
            assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                F"{full_name} has size {value.shape}, but"
                F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
            )
            UpperCAmelCase      	=		value
            logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."					)
    else:
        unused_weights.append(_a					)





def 						snake_case_							(_a     :							Dict					):
    UpperCAmelCase      	=		HubertConfig()
    UpperCAmelCase      	=		model.config

    UpperCAmelCase      	=		fs_config.activation_dropout
    UpperCAmelCase      	=		False
    UpperCAmelCase      	=		fs_config.attention_dropout
    UpperCAmelCase      	=		False
    UpperCAmelCase      	=		eval(fs_config.extractor_conv_feature_layers					)
    UpperCAmelCase      	=		[x[0] for x in conv_layers]
    UpperCAmelCase      	=		[x[1] for x in conv_layers]
    UpperCAmelCase      	=		[x[2] for x in conv_layers]
    UpperCAmelCase      	=		"""gelu"""
    UpperCAmelCase      	=		"""layer""" if fs_config.extractor_mode == """layer_norm""" else """group"""
    UpperCAmelCase      	=		False
    UpperCAmelCase      	=		0.0
    UpperCAmelCase      	=		0.0
    UpperCAmelCase      	=		fs_config.activation_fn
    UpperCAmelCase      	=		fs_config.dropout
    UpperCAmelCase      	=		fs_config.encoder_embed_dim
    UpperCAmelCase      	=		0.02
    UpperCAmelCase      	=		fs_config.encoder_ffn_embed_dim
    UpperCAmelCase      	=		1E-5
    UpperCAmelCase      	=		0.0
    UpperCAmelCase      	=		fs_config.encoder_attention_heads
    UpperCAmelCase      	=		fs_config.conv_pos_groups
    UpperCAmelCase      	=		fs_config.conv_pos
    UpperCAmelCase      	=		len(_a					)
    UpperCAmelCase      	=		fs_config.encoder_layers

    return config





@torch.no_grad()
def 						snake_case_							(_a     :							Optional[Any]   ,       _a     :							str=None					):
    UpperCAmelCase      	=		distilhubert().model.model

    if config_path is not None:
        UpperCAmelCase      	=		HubertConfig.from_pretrained(_a					)
    else:
        UpperCAmelCase      	=		convert_config(_a					)
    UpperCAmelCase      	=		model.eval()

    UpperCAmelCase      	=		WavaVecaFeatureExtractor(
        feature_size=1   ,       sampling_rate=1_6_0_0_0   ,       padding_value=0   ,       do_normalize=_a   ,       return_attention_mask=_a   ,       )
    UpperCAmelCase      	=		HubertModel(_a					)

    recursively_load_weights(_a   ,       _a					)

    feature_extractor.save_pretrained(_a					)
    hf_model.save_pretrained(_a					)


if __name__ == "__main__":
   A			   =argparse.ArgumentParser()
   parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
   parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
   A			   =parser.parse_args()
   convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)










'''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     :							str					):
    print(F"Reading saved model from {model_file}"					)
    UpperCAmelCase      	=		torch.load(_a   ,       map_location=lambda _a   ,       _a					: default_restore_location(_a   ,       '''cpu'''					)					)
    return CheckpointState(**_a					)


class       _a  :
       def __init__(     self						:     List[Any]       ,    lowercase						:     Path    ):



           '''simple docstring'''

           UpperCAmelCase      	=		src_file
       def    A				(     self						:     str    ):



           '''simple docstring'''

           raise NotImplementedError







       @staticmethod
       def    A				(     lowercase						:     str       ,    *lowercase						:     Tuple       ,    **lowercase						:     Union[str, Any]    ):



           '''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  (     __a			):
       def    A				(     self						:     int    ):



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






class       _a  (     __a			):
       def    A				(     self						:     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(lowercase    ):
                   UpperCAmelCase      	=		key[len(lowercase    ) :]
                   if not key.startswith('''encode_proj.'''    ):
                       UpperCAmelCase      	=		'''bert_model.''' + key
                   UpperCAmelCase      	=		value
           encoder.load_state_dict(lowercase    )
           return model






class       _a  (     __a			):
       def    A				(     self						:     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(lowercase    )
           return model






def 						snake_case_							(_a     :							str   ,       _a     :							Path   ,       _a     :							Path					):
    UpperCAmelCase      	=		Path(_a					)
    dest_dir.mkdir(exist_ok=_a					)

    UpperCAmelCase      	=		DPRState.from_type(_a   ,       src_file=_a					)
    UpperCAmelCase      	=		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)




