import os
import sys
import unittest


UpperCAmelCase_								=							os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
UpperCAmelCase_								=							os.path.join(git_repo_path, '''src''', '''transformers''')

UpperCAmelCase_								=							'''
{0} = None
'''

UpperCAmelCase_								=							'''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


UpperCAmelCase_								=							'''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''





class      lowerCAmelCase						(					unittest.TestCase			):



     def 			a__  (					self       ):
            _A=	find_backend('    _import_structure["models.albert"].append("AlbertTokenizerFast")'       )
            self.assertIsNone(lowerCAmelCase__       )

            _A=	find_backend('    if not is_tokenizers_available():'       )
            self.assertEqual(lowerCAmelCase__				,      'tokenizers'       )

            _A=	find_backend('    if not is_tensorflow_text_available():'       )
            self.assertEqual(lowerCAmelCase__				,      'tensorflow_text'       )

            _A=	find_backend('    if not (is_sentencepiece_available() and is_tokenizers_available()):'       )
            self.assertEqual(lowerCAmelCase__				,      'sentencepiece_and_tokenizers'       )

            _A=	find_backend(
                '    if not (is_sentencepiece_available() and is_tensorflow_text_available()):'       )
            self.assertEqual(lowerCAmelCase__				,      'sentencepiece_and_tensorflow_text'       )

            _A=	find_backend(
                '    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):'       )
            self.assertEqual(lowerCAmelCase__				,      'sentencepiece_and_tokenizers_and_vision'       )



     def 			a__  (					self       ):
            _A=	read_init()
            # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
            self.assertIn('torch'				,      lowerCAmelCase__       )
            self.assertIn('tensorflow_text'				,      lowerCAmelCase__       )
            self.assertIn('sentencepiece_and_tokenizers'				,      lowerCAmelCase__       )

            # Likewise, we can't assert on the exact content of a key
            self.assertIn('BertModel'				,      objects['torch']       )
            self.assertIn('TFBertModel'				,      objects['tf']       )
            self.assertIn('FlaxBertModel'				,      objects['flax']       )
            self.assertIn('BertModel'				,      objects['torch']       )
            self.assertIn('TFBertTokenizer'				,      objects['tensorflow_text']       )
            self.assertIn('convert_slow_tokenizer'				,      objects['sentencepiece_and_tokenizers']       )



     def 			a__  (					self       ):
            _A=	create_dummy_object('CONSTANT'				,      '\'torch\''       )
            self.assertEqual(lowerCAmelCase__				,      '\nCONSTANT = None\n'       )

            _A=	create_dummy_object('function'				,      '\'torch\''       )
            self.assertEqual(
                lowerCAmelCase__				,      '\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'       )

            _A=	'\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n'
            _A=	create_dummy_object('FakeClass'				,      '\'torch\''       )
            self.assertEqual(lowerCAmelCase__				,      lowerCAmelCase__       )





     def 			a__  (					self       ):
            _A=	'# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = ["torch"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, ["torch"])\n'
            _A=	create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']}       )
            self.assertEqual(dummy_files['torch']				,      lowerCAmelCase__       )
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, 11]:
            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)