



"""simple docstring"""
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
   from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


_UpperCAmelCase     =			logging.get_logger(__name__)

_UpperCAmelCase     =			{
    'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json',
    'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json',
    'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json',
    'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json',
    'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json',
    'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json',
}
class 					a				(  UpperCAmelCase__       ):
  UpperCamelCase	:				Dict     						=					'bloom'
  UpperCamelCase	:				Any     						=					['past_key_values']
  UpperCamelCase	:				List[Any]     						=					{
      'num_hidden_layers': 'n_layer',
      'num_attention_heads': 'n_head',
  }



  def __init__(						self :					Dict       ,		lowerCAmelCase :					int=25_0880       ,		lowerCAmelCase :					Tuple=64       ,		lowerCAmelCase :					Tuple=2       ,		lowerCAmelCase :					str=8       ,		lowerCAmelCase :					Union[str, Any]=1E-5       ,		lowerCAmelCase :					str=0.0_2       ,		lowerCAmelCase :					Union[str, Any]=True       ,		lowerCAmelCase :					Union[str, Any]=1       ,		lowerCAmelCase :					List[Any]=2       ,		lowerCAmelCase :					int=False       ,		lowerCAmelCase :					Dict=0.0       ,		lowerCAmelCase :					Optional[int]=0.0       ,		lowerCAmelCase :					Any=1       ,		lowerCAmelCase :					Optional[int]=False       ,		**lowerCAmelCase :					Dict       ,		)     ->					List[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: str     			=vocab_size
     # Backward compatibility with n_embed kwarg
     SCREAMING_SNAKE_CASE_: Tuple     			=kwargs.pop("""n_embed"""       ,		_lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: str     			=hidden_size if n_embed is None else n_embed
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=n_layer
     SCREAMING_SNAKE_CASE_: Optional[int]     			=n_head
     SCREAMING_SNAKE_CASE_: Optional[int]     			=layer_norm_epsilon
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=initializer_range
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=use_cache
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=pretraining_tp
     SCREAMING_SNAKE_CASE_: List[str]     			=apply_residual_connection_post_layernorm
     SCREAMING_SNAKE_CASE_: List[Any]     			=hidden_dropout
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=attention_dropout

     SCREAMING_SNAKE_CASE_: str     			=bos_token_id
     SCREAMING_SNAKE_CASE_: Dict     			=eos_token_id
     SCREAMING_SNAKE_CASE_: int     			=slow_but_exact

     super().__init__(bos_token_id=_lowerCAmelCase       ,		eos_token_id=_lowerCAmelCase       ,		**_lowerCAmelCase		)







class 					a				(  UpperCAmelCase__       ):
  UpperCamelCase	:				List[Any]     						=					version.parse('1.12'       )



  def __init__(						self :					List[Any]       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					int = "default"       ,		lowerCAmelCase :					Dict = None       ,		lowerCAmelCase :					Optional[Any] = False       ,		)     ->					int:


     '''simple docstring'''




     super().__init__(_lowerCAmelCase       ,		task=_lowerCAmelCase       ,		patching_specs=_lowerCAmelCase       ,		use_past=_lowerCAmelCase		)
     if not getattr(self._config       ,		"""pad_token_id"""       ,		_lowerCAmelCase		):
        # TODO: how to do that better?
        SCREAMING_SNAKE_CASE_: Optional[Any]     			=0



  @property
  def 	lowerCamelCase__       (						self :					Optional[int]		)     ->					Optional[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[Any]     			=OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}		)
     if self.use_past:
        # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
        self.fill_with_past_key_values_(_lowerCAmelCase       ,		direction="""inputs"""       ,		inverted_values_shape=_lowerCAmelCase		)
        SCREAMING_SNAKE_CASE_: int     			={0: """batch""", 1: """past_sequence + sequence"""}
     else:
        SCREAMING_SNAKE_CASE_: Any     			={0: """batch""", 1: """sequence"""}

     return common_inputs



  @property
  def 	lowerCamelCase__       (						self :					List[Any]		)     ->					List[str]:


     '''simple docstring'''




     return self._config.n_layer



  @property
  def 	lowerCamelCase__       (						self :					Union[str, Any]		)     ->					List[str]:


     '''simple docstring'''




     return self._config.n_head



  @property
  def 	lowerCamelCase__       (						self :					Any		)     ->					List[str]:


     '''simple docstring'''




     return 1E-3



  def 	lowerCamelCase__       (						self :					Dict       ,		lowerCAmelCase :					Dict       ,		lowerCAmelCase :					List[str] = -1       ,		lowerCAmelCase :					Union[str, Any] = -1       ,		lowerCAmelCase :					str = False       ,		lowerCAmelCase :					Union[str, Any] = None       ,		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[str]     			=super(_lowerCAmelCase       ,		self		).generate_dummy_inputs(
         _lowerCAmelCase       ,		batch_size=_lowerCAmelCase       ,		seq_length=_lowerCAmelCase       ,		is_pair=_lowerCAmelCase       ,		framework=_lowerCAmelCase		)

     # We need to order the input in the way they appears in the forward()
     SCREAMING_SNAKE_CASE_: List[Any]     			=OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}		)

     # Need to add the past_keys
     if self.use_past:
        if not is_torch_available():
           raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""		)
        else:
           import torch

           SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: Dict     			=common_inputs["""input_ids"""].shape
           # Not using the same length for past_key_values
           SCREAMING_SNAKE_CASE_: Dict     			=seqlen + 2
           SCREAMING_SNAKE_CASE_: Optional[int]     			=self._config.hidden_size // self.num_attention_heads
           SCREAMING_SNAKE_CASE_: Optional[Any]     			=(
               batch * self.num_attention_heads,
               head_dim,
               past_key_values_length,
           )
           SCREAMING_SNAKE_CASE_: Union[str, Any]     			=(
               batch * self.num_attention_heads,
               past_key_values_length,
               head_dim,
           )
           SCREAMING_SNAKE_CASE_: List[str]     			=[
               (torch.zeros(_lowerCAmelCase		), torch.zeros(_lowerCAmelCase		)) for _ in range(self.num_layers		)
           ]

     SCREAMING_SNAKE_CASE_: int     			=common_inputs["""attention_mask"""]
     if self.use_past:
        SCREAMING_SNAKE_CASE_: int     			=ordered_inputs["""attention_mask"""].dtype
        SCREAMING_SNAKE_CASE_: Optional[int]     			=torch.cat(
            [ordered_inputs["""attention_mask"""], torch.ones(_lowerCAmelCase       ,		_lowerCAmelCase       ,		dtype=_lowerCAmelCase		)]       ,		dim=1		)

     return ordered_inputs





  @property
  def 	lowerCamelCase__       (						self :					Dict		)     ->					List[Any]:


     '''simple docstring'''




     return 13








"""simple docstring"""
import argparse

import torch

from transformers import BertForMaskedLM


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

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

   _UpperCAmelCase     =			model.state_dict()
   _UpperCAmelCase     =			{}

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

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

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

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

   _UpperCAmelCase     =			state_dict["""cls.predictions.decoder.weight"""]
   _UpperCAmelCase     =			state_dict["""cls.predictions.bias"""]
   if args.vocab_transform:
      for w in ["weight", "bias"]:
         _UpperCAmelCase     =			state_dict[f"""cls.predictions.transform.dense.{w}"""]
         _UpperCAmelCase     =			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)



