



"""simple docstring"""






# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__snake_case				:  Tuple =       {
    'configuration_efficientnet': [
        'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'EfficientNetConfig',
        'EfficientNetOnnxConfig',
    ]
}

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__snake_case				:  Dict =       ['EfficientNetImageProcessor']

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__snake_case				:  Optional[Any] =       [
	    'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST',
	    'EfficientNetForImageClassification',
	    'EfficientNetModel',
	    'EfficientNetPreTrainedModel',
	]

if TYPE_CHECKING:
	from .configuration_efficientnet import (
	    EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    EfficientNetConfig,
	    EfficientNetOnnxConfig,
	)

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .image_processing_efficientnet import EfficientNetImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_efficientnet import (
		    EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
		    EfficientNetForImageClassification,
		    EfficientNetModel,
		    EfficientNetPreTrainedModel,
		)

else:
	import sys

	__snake_case				:  Union[str, Any] =       _LazyModule(__name__, globals()['__file__'], _import_structure)




"""simple docstring"""






import argparse

import torch

from transformers import BertForMaskedLM


if __name__ == "__main__":
	__snake_case				:  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')
	__snake_case				:  List[Any] =       parser.parse_args()

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

	__snake_case				:  List[Any] =       model.state_dict()
	__snake_case				:  Any =       {}

	for w in ["word_embeddings", "position_embeddings"]:
		__snake_case				:  List[str] =       state_dict[F"""{prefix}.embeddings.{w}.weight"""]
	for w in ["weight", "bias"]:
		__snake_case				:  Optional[int] =       state_dict[F"""{prefix}.embeddings.LayerNorm.{w}"""]

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

			__snake_case				:  Any =       state_dict[
			    F"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}"""
			]
			__snake_case				:  Union[str, Any] =       state_dict[
			    F"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}"""
			]

			__snake_case				:  Union[str, Any] =       state_dict[
			    F"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}"""
			]
			__snake_case				:  Any =       state_dict[
			    F"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}"""
			]
			__snake_case				:  Optional[int] =       state_dict[
			    F"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}"""
			]
		std_idx += 1

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