


"""simple docstring"""







import argparse

import torch

from transformers import BertForMaskedLM


if __name__ == "__main__":
 __lowercase    					=      argparse.ArgumentParser(
     description=(
         """Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned"""
         """ Distillation"""
     )
 )
 parser.add_argument("""--model_type""", default="""bert""", choices=["""bert"""])
 parser.add_argument("""--model_name""", default="""bert-base-uncased""", type=str)
 parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_bert-base-uncased_0247911.pth""", type=str)
 parser.add_argument("""--vocab_transform""", action="""store_true""")
 __lowercase    					=      parser.parse_args()

 if args.model_type == "bert":
  __lowercase    					=      BertForMaskedLM.from_pretrained(args.model_name)
  __lowercase    					=      """bert"""
 else:
  raise ValueError("""args.model_type should be \"bert\".""")

 __lowercase    					=      model.state_dict()
 __lowercase    					=      {}

 for w in ["word_embeddings", "position_embeddings"]:
  __lowercase    					=      state_dict[f'''{prefix}.embeddings.{w}.weight''']
 for w in ["weight", "bias"]:
  __lowercase    					=      state_dict[f'''{prefix}.embeddings.LayerNorm.{w}''']

 __lowercase    					=      0
 for teacher_idx in [0, 2, 4, 7, 9, 11]:
  for w in ["weight", "bias"]:
   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}'''
   ]
   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}'''
   ]
   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}'''
   ]

   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}'''
   ]
   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}'''
   ]

   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}'''
   ]
   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}'''
   ]
   __lowercase    					=      state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}'''
   ]
  std_idx += 1

 __lowercase    					=      state_dict["""cls.predictions.decoder.weight"""]
 __lowercase    					=      state_dict["""cls.predictions.bias"""]
 if args.vocab_transform:
  for w in ["weight", "bias"]:
   __lowercase    					=      state_dict[f'''cls.predictions.transform.dense.{w}''']
   __lowercase    					=      state_dict[f'''cls.predictions.transform.LayerNorm.{w}''']

 print(f'''N layers selected for distillation: {std_idx}''')
 print(f'''Number of params transferred for distillation: {len(compressed_sd.keys())}''')

 print(f'''Save transferred checkpoint to {args.dump_checkpoint}.''')
 torch.save(compressed_sd, args.dump_checkpoint)










"""simple docstring"""







from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowercase    					=      logging.get_logger(__name__)

__lowercase    					=      {
    """facebook/dpr-ctx_encoder-single-nq-base""": (
        """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"""
    ),
    """facebook/dpr-question_encoder-single-nq-base""": (
        """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"""
    ),
    """facebook/dpr-reader-single-nq-base""": (
        """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"""
    ),
    """facebook/dpr-ctx_encoder-multiset-base""": (
        """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"""
    ),
    """facebook/dpr-question_encoder-multiset-base""": (
        """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"""
    ),
    """facebook/dpr-reader-multiset-base""": (
        """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"""
    ),
}






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase       :							int	=       """dpr"""






    def __init__(					self				:    List[Any]				, __UpperCAmelCase				:    int=30522				, __UpperCAmelCase				:    Union[str, Any]=768				, __UpperCAmelCase				:    Dict=12				, __UpperCAmelCase				:    List[str]=12				, __UpperCAmelCase				:    Any=3072				, __UpperCAmelCase				:    Optional[int]="gelu"				, __UpperCAmelCase				:    Any=0.1				, __UpperCAmelCase				:    Union[str, Any]=0.1				, __UpperCAmelCase				:    str=512				, __UpperCAmelCase				:    List[str]=2				, __UpperCAmelCase				:    Tuple=0.02				, __UpperCAmelCase				:    List[str]=1e-12				, __UpperCAmelCase				:    List[str]=0				, __UpperCAmelCase				:    str="absolute"				, __UpperCAmelCase				:    int = 0				, **__UpperCAmelCase				:    Tuple				, ):
      super().__init__(pad_token_id=__UpperCAmelCase				, **__UpperCAmelCase)

      a						:		List[Any]      							=			vocab_size
      a						:		Optional[Any]      							=			hidden_size
      a						:		Union[str, Any]      							=			num_hidden_layers
      a						:		Dict      							=			num_attention_heads
      a						:		int      							=			hidden_act
      a						:		Any      							=			intermediate_size
      a						:		Any      							=			hidden_dropout_prob
      a						:		Dict      							=			attention_probs_dropout_prob
      a						:		Any      							=			max_position_embeddings
      a						:		Union[str, Any]      							=			type_vocab_size
      a						:		Optional[Any]      							=			initializer_range
      a						:		Dict      							=			layer_norm_eps
      a						:		int      							=			projection_dim
      a						:		str      							=			position_embedding_type






