


'''simple docstring'''


from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
	import tensorflow as tf

	from transformers import TFBlipTextModel
	from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST






class 	lowerCAmelCase__			:




			def __init__(		self  :     Optional[int]	,  lowerCamelCase__  :     Optional[int]	,  lowerCamelCase__  :     Optional[int]=12	,  lowerCamelCase__  :     Union[str, Any]=7	,  lowerCamelCase__  :     List[Any]=True	,  lowerCamelCase__  :     Optional[int]=True	,  lowerCamelCase__  :     Dict=True	,  lowerCamelCase__  :     Dict=99	,  lowerCamelCase__  :     str=32	,  lowerCamelCase__  :     List[str]=32	,  lowerCamelCase__  :     Dict=2	,  lowerCamelCase__  :     int=4	,  lowerCamelCase__  :     Any=37	,  lowerCamelCase__  :     Optional[Any]=0.1	,  lowerCamelCase__  :     Any=0.1	,  lowerCamelCase__  :     Tuple=5_12	,  lowerCamelCase__  :     List[Any]=0.0_2	,  lowerCamelCase__  :     List[Any]=0	,  lowerCamelCase__  :     Optional[int]=None	,  )   ->List[Any]:



					'''simple docstring'''







					_UpperCAmelCase		:       List[str]								=      parent
					_UpperCAmelCase		:       List[Any]								=      batch_size
					_UpperCAmelCase		:       str								=      seq_length
					_UpperCAmelCase		:       Dict								=      is_training
					_UpperCAmelCase		:       str								=      use_input_mask
					_UpperCAmelCase		:       Optional[Any]								=      use_labels
					_UpperCAmelCase		:       Union[str, Any]								=      vocab_size
					_UpperCAmelCase		:       int								=      hidden_size
					_UpperCAmelCase		:       Optional[int]								=      projection_dim
					_UpperCAmelCase		:       Dict								=      num_hidden_layers
					_UpperCAmelCase		:       Optional[int]								=      num_attention_heads
					_UpperCAmelCase		:       Any								=      intermediate_size
					_UpperCAmelCase		:       Optional[Any]								=      dropout
					_UpperCAmelCase		:       Optional[Any]								=      attention_dropout
					_UpperCAmelCase		:       Tuple								=      max_position_embeddings
					_UpperCAmelCase		:       int								=      initializer_range
					_UpperCAmelCase		:       List[Any]								=      scope
					_UpperCAmelCase		:       int								=      bos_token_id




			def 							lowerCAmelCase__    (		self  :     Optional[Any] )   ->Dict:



					'''simple docstring'''







					_UpperCAmelCase		:       List[str]								=      ids_tensor([self.batch_size, self.seq_length]	,  self.vocab_size )

					_UpperCAmelCase		:       str								=      None
					if self.use_input_mask:
							_UpperCAmelCase		:       Union[str, Any]								=      random_attention_mask([self.batch_size, self.seq_length] )

					if input_mask is not None:
							_UpperCAmelCase		:       int								=      input_mask.numpy()
							_UpperCAmelCase		:       List[Any]								=      input_mask.shape
							_UpperCAmelCase		:       Dict								=      np.random.randint(1	,  seq_length - 1	,  size=(batch_size,) )
							for batch_idx, start_index in enumerate(lowerCamelCase__ ):
									_UpperCAmelCase		:       List[str]								=      1
									_UpperCAmelCase		:       List[Any]								=      0

					_UpperCAmelCase		:       List[Any]								=      self.get_config()

					return config, input_ids, tf.convert_to_tensor(lowerCamelCase__ )




			def 							lowerCAmelCase__    (		self  :     str )   ->List[str]:



					'''simple docstring'''







					return BlipTextConfig(
					    vocab_size=self.vocab_size	,  hidden_size=self.hidden_size	,  projection_dim=self.projection_dim	,  num_hidden_layers=self.num_hidden_layers	,  num_attention_heads=self.num_attention_heads	,  intermediate_size=self.intermediate_size	,  dropout=self.dropout	,  attention_dropout=self.attention_dropout	,  max_position_embeddings=self.max_position_embeddings	,  initializer_range=self.initializer_range	,  bos_token_id=self.bos_token_id	,  )




			def 							lowerCAmelCase__    (		self  :     Any	,  lowerCamelCase__  :     int	,  lowerCamelCase__  :     str	,  lowerCamelCase__  :     Tuple )   ->Dict:



					'''simple docstring'''







					_UpperCAmelCase		:       int								=      TFBlipTextModel(config=lowerCamelCase__ )
					_UpperCAmelCase		:       Optional[int]								=      model(lowerCamelCase__	,  attention_mask=lowerCamelCase__	,  training=lowerCamelCase__ )
					_UpperCAmelCase		:       Dict								=      model(lowerCamelCase__	,  training=lowerCamelCase__ )
					self.parent.assertEqual(result.last_hidden_state.shape	,  (self.batch_size, self.seq_length, self.hidden_size) )
					self.parent.assertEqual(result.pooler_output.shape	,  (self.batch_size, self.hidden_size) )






			def 							lowerCAmelCase__    (		self  :     Any )   ->Tuple:



					'''simple docstring'''







					_UpperCAmelCase		:       Union[str, Any]								=      self.prepare_config_and_inputs()
					_UpperCAmelCase		:       Tuple								=      config_and_inputs
					_UpperCAmelCase		:       Optional[Any]								=      {"input_ids": input_ids, "attention_mask": input_mask}
					return config, inputs_dict






@require_tf
class 	lowerCAmelCase__			(			UpperCAmelCase__    ,       unittest.TestCase	):
			lowerCAmelCase :	Tuple          =     (TFBlipTextModel,) if is_tf_available() else ()
			lowerCAmelCase :	List[str]          =     False
			lowerCAmelCase :	List[Any]          =     False
			lowerCAmelCase :	Optional[Any]          =     False




			def 							lowerCAmelCase__    (		self  :     str )   ->List[str]:



					'''simple docstring'''







					_UpperCAmelCase		:       Optional[Any]								=      BlipTextModelTester(self )
					_UpperCAmelCase		:       Any								=      ConfigTester(self	,  config_class=lowerCamelCase__	,  hidden_size=37 )




			def 							lowerCAmelCase__    (		self  :     Optional[Any] )   ->Union[str, Any]:



					'''simple docstring'''







					self.config_tester.run_common_tests()




			def 							lowerCAmelCase__    (		self  :     Optional[int] )   ->Tuple:



					'''simple docstring'''







					_UpperCAmelCase		:       List[str]								=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCamelCase__ )




			def 							lowerCAmelCase__    (		self  :     Optional[Any] )   ->Optional[int]:



					'''simple docstring'''







					pass




			def 							lowerCAmelCase__    (		self  :     Tuple )   ->Dict:



					'''simple docstring'''







					pass




			@unittest.skip(reason="Blip does not use inputs_embeds" )
			def 							lowerCAmelCase__    (		self  :     Optional[int] )   ->List[str]:



					'''simple docstring'''







					pass




			@unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" )
			def 							lowerCAmelCase__    (		self  :     str )   ->Any:



					'''simple docstring'''







					pass




			@unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" )
			def 							lowerCAmelCase__    (		self  :     Union[str, Any] )   ->Optional[int]:



					'''simple docstring'''







					pass




			@slow
			def 							lowerCAmelCase__    (		self  :     int )   ->Optional[Any]:



					'''simple docstring'''







					for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							_UpperCAmelCase		:       Tuple								=      TFBlipTextModel.from_pretrained(lowerCamelCase__ )
							self.assertIsNotNone(lowerCamelCase__ )






			def 							lowerCAmelCase__    (		self  :     str	,  lowerCamelCase__  :     Tuple=True )   ->Dict:



					'''simple docstring'''







					super().test_pt_tf_model_equivalence(allow_missing_keys=lowerCamelCase__ )







'''simple docstring'''


import argparse

import torch

from transformers import BertForMaskedLM


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

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

						lowerCamelCase__    	=     model.state_dict()
						lowerCamelCase__    	=     {}

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

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

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

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

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



