
'''simple docstring'''






import argparse

import torch

from transformers import BertForMaskedLM


if __name__ == "__main__":
 UpperCAmelCase_							: Optional[Any] =							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_							: Optional[int] =							parser.parse_args()

 if args.model_type == "bert":
  UpperCAmelCase_							: Any =							BertForMaskedLM.from_pretrained(args.model_name)
  UpperCAmelCase_							: Optional[int] =							"""bert"""
 else:
  raise ValueError('args.model_type should be \"bert\".')

 UpperCAmelCase_							: str =							model.state_dict()
 UpperCAmelCase_							: str =							{}

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

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

   UpperCAmelCase_							: Dict =							state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}'''
   ]
   UpperCAmelCase_							: Union[str, Any] =							state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}'''
   ]

   UpperCAmelCase_							: Union[str, Any] =							state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}'''
   ]
   UpperCAmelCase_							: Union[str, Any] =							state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}'''
   ]
   UpperCAmelCase_							: Optional[Any] =							state_dict[
       f'''{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}'''
   ]
  std_idx += 1

 UpperCAmelCase_							: Optional[Any] =							state_dict["""cls.predictions.decoder.weight"""]
 UpperCAmelCase_							: Tuple =							state_dict["""cls.predictions.bias"""]
 if args.vocab_transform:
  for w in ["weight", "bias"]:
   UpperCAmelCase_							: int =							state_dict[f'''cls.predictions.transform.dense.{w}''']
   UpperCAmelCase_							: Optional[int] =							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'''
import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
					import jax.numpy as jnp

					from transformers.models.distilbert.modeling_flax_distilbert import (
					    FlaxDistilBertForMaskedLM,
					    FlaxDistilBertForMultipleChoice,
					    FlaxDistilBertForQuestionAnswering,
					    FlaxDistilBertForSequenceClassification,
					    FlaxDistilBertForTokenClassification,
					    FlaxDistilBertModel,
					)




class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				def __init__(     self							,      a_							,      a_=1_3							,      a_=7							,      a_=True							,      a_=True							,      a_=True							,      a_=True							,      a_=9_9							,      a_=3_2							,      a_=5							,      a_=4							,      a_=3_7							,      a_="gelu"							,      a_=0.1							,      a_=0.1							,      a_=5_1_2							,      a_=1_6							,      a_=2							,      a_=0.02							,      a_=4							,      )    ->  Tuple:
					lowercase						:		Optional[Any]   					=		parent
					lowercase						:		int   					=		batch_size
					lowercase						:		int   					=		seq_length
					lowercase						:		List[str]   					=		is_training
					lowercase						:		str   					=		use_attention_mask
					lowercase						:		List[str]   					=		use_token_type_ids
					lowercase						:		Optional[Any]   					=		use_labels
					lowercase						:		Dict   					=		vocab_size
					lowercase						:		Union[str, Any]   					=		hidden_size
					lowercase						:		int   					=		num_hidden_layers
					lowercase						:		Optional[Any]   					=		num_attention_heads
					lowercase						:		Optional[Any]   					=		intermediate_size
					lowercase						:		int   					=		hidden_act
					lowercase						:		Dict   					=		hidden_dropout_prob
					lowercase						:		Optional[Any]   					=		attention_probs_dropout_prob
					lowercase						:		Dict   					=		max_position_embeddings
					lowercase						:		Tuple   					=		type_vocab_size
					lowercase						:		int   					=		type_sequence_label_size
					lowercase						:		Optional[Any]   					=		initializer_range
					lowercase						:		Union[str, Any]   					=		num_choices

				def 	a__		(     self							)    ->  Optional[int]:
					lowercase						:		List[Any]   					=		ids_tensor([self.batch_size, self.seq_length]							,      self.vocab_size							)

					lowercase						:		Any   					=		None
					if self.use_attention_mask:
						lowercase						:		str   					=		random_attention_mask([self.batch_size, self.seq_length]							)

					lowercase						:		Optional[Any]   					=		DistilBertConfig(
					    vocab_size=self.vocab_size							,      dim=self.hidden_size							,      n_layers=self.num_hidden_layers							,      n_heads=self.num_attention_heads							,      hidden_dim=self.intermediate_size							,      hidden_act=self.hidden_act							,      dropout=self.hidden_dropout_prob							,      attention_dropout=self.attention_probs_dropout_prob							,      max_position_embeddings=self.max_position_embeddings							,      initializer_range=self.initializer_range							,      tie_weights_=a_							,      )

					return config, input_ids, attention_mask


				def 	a__		(     self							)    ->  List[str]:
					lowercase						:		Dict   					=		self.prepare_config_and_inputs()
					lowercase					,		lowercase					,		lowercase						:		Dict   					=		config_and_inputs
					lowercase						:		Any   					=		{"input_ids": input_ids, "attention_mask": attention_mask}
					return config, inputs_dict




@require_flax
class        _UpperCamelCase	(    SCREAMING_SNAKE_CASE						,			unittest.TestCase):


				'''simple docstring'''


				_snake_case						       =				(
				    (
				        FlaxDistilBertModel,
				        FlaxDistilBertForMaskedLM,
				        FlaxDistilBertForMultipleChoice,
				        FlaxDistilBertForQuestionAnswering,
				        FlaxDistilBertForSequenceClassification,
				        FlaxDistilBertForTokenClassification,
				        FlaxDistilBertForQuestionAnswering,
				    )
				    if is_flax_available()
				    else ()
				)

				def 	a__		(     self							)    ->  Dict:
					lowercase						:		Optional[int]   					=		FlaxDistilBertModelTester(self							)


				@slow
				def 	a__		(     self							)    ->  Union[str, Any]:
					for model_class_name in self.all_model_classes:
						lowercase						:		int   					=		model_class_name.from_pretrained("distilbert-base-uncased"							)
						lowercase						:		Tuple   					=		model(np.ones((1, 1)							)							)
						self.assertIsNotNone(a_							)




@require_flax
class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				@slow
				def 	a__		(     self							)    ->  Union[str, Any]:
					lowercase						:		str   					=		FlaxDistilBertModel.from_pretrained("distilbert-base-uncased"							)
					lowercase						:		int   					=		np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]							)
					lowercase						:		int   					=		np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
					lowercase						:		List[str]   					=		model(a_							,      attention_mask=a_							)[0]
					lowercase						:		int   					=		(1, 1_1, 7_6_8)
					self.assertEqual(output.shape							,      a_							)
					lowercase						:		List[str]   					=		np.array([[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]]							)

					self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]							,      a_							,      atol=1e-4							)							)


