





import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
       import torch

if is_tf_available():
       import tensorflow as tf







@require_vision
@require_torchvision
class       __A							(   unittest.TestCase	):




      """simple docstring"""







      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Tuple						=		tempfile.mkdtemp()
             _lowerCamelCase				:  List[Any]						=		SamImageProcessor()
             _lowerCamelCase				:  List[Any]						=		SamProcessor(a__)
             processor.save_pretrained(self.tmpdirname)


      def 					__snake_case      (		self   ,				**a__):



             """simple docstring"""





             return AutoProcessor.from_pretrained(self.tmpdirname   ,				**a__).image_processor


      def 					__snake_case      (		self):



             """simple docstring"""





             shutil.rmtree(self.tmpdirname)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[Any]						=		[np.random.randint(255   ,				size=(3, 30, 400)   ,				dtype=np.uinta)]

             _lowerCamelCase				:  Any						=		[Image.fromarray(np.moveaxis(a__   ,				0   ,				-1)) for x in image_inputs]

             return image_inputs


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		SamProcessor(image_processor=self.get_image_processor())
             processor.save_pretrained(self.tmpdirname)

             _lowerCamelCase				:  List[str]						=		self.get_image_processor(do_normalize=a__   ,				padding_value=1.0)

             _lowerCamelCase				:  List[str]						=		SamProcessor.from_pretrained(self.tmpdirname   ,				do_normalize=a__   ,				padding_value=1.0)

             self.assertEqual(processor.image_processor.to_json_string()   ,				image_processor_add_kwargs.to_json_string())
             self.assertIsInstance(processor.image_processor   ,				a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		self.get_image_processor()

             _lowerCamelCase				:  Union[str, Any]						=		SamProcessor(image_processor=a__)

             _lowerCamelCase				:  List[str]						=		self.prepare_image_inputs()

             _lowerCamelCase				:  List[str]						=		image_processor(a__   ,				return_tensors='''np''')
             _lowerCamelCase				:  str						=		processor(images=a__   ,				return_tensors='''np''')

             input_feat_extract.pop('''original_sizes''')  # pop original_sizes as it is popped in the processor
             input_feat_extract.pop('''reshaped_input_sizes''')  # pop original_sizes as it is popped in the processor

             for key in input_feat_extract.keys():
                    self.assertAlmostEqual(input_feat_extract[key].sum()   ,				input_processor[key].sum()   ,				delta=1e-2)



      @require_torch
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  str						=		self.get_image_processor()

             _lowerCamelCase				:  Union[str, Any]						=		SamProcessor(image_processor=a__)
             _lowerCamelCase				:  Union[str, Any]						=		[torch.ones((1, 3, 5, 5))]

             _lowerCamelCase				:  Tuple						=		[[1764, 2646]]

             _lowerCamelCase				:  Optional[Any]						=		[[683, 1024]]
             _lowerCamelCase				:  List[Any]						=		processor.post_process_masks(a__   ,				a__   ,				a__)
             self.assertEqual(masks[0].shape   ,				(1, 3, 1764, 2646))

             _lowerCamelCase				:  str						=		processor.post_process_masks(
                 a__   ,				torch.tensor(a__)   ,				torch.tensor(a__))
             self.assertEqual(masks[0].shape   ,				(1, 3, 1764, 2646))

             # should also work with np
             _lowerCamelCase				:  List[str]						=		[np.ones((1, 3, 5, 5))]
             _lowerCamelCase				:  List[Any]						=		processor.post_process_masks(a__   ,				np.array(a__)   ,				np.array(a__))

             self.assertEqual(masks[0].shape   ,				(1, 3, 1764, 2646))

             _lowerCamelCase				:  Any						=		[[1, 0], [0, 1]]
             with self.assertRaises(a__):
                    _lowerCamelCase				:  Tuple						=		processor.post_process_masks(a__   ,				np.array(a__)   ,				np.array(a__))







@require_vision
@require_tf
class       __A							(   unittest.TestCase	):




      """simple docstring"""







      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		tempfile.mkdtemp()
             _lowerCamelCase				:  List[str]						=		SamImageProcessor()
             _lowerCamelCase				:  List[str]						=		SamProcessor(a__)
             processor.save_pretrained(self.tmpdirname)


      def 					__snake_case      (		self   ,				**a__):



             """simple docstring"""





             return AutoProcessor.from_pretrained(self.tmpdirname   ,				**a__).image_processor


      def 					__snake_case      (		self):



             """simple docstring"""





             shutil.rmtree(self.tmpdirname)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Tuple						=		[np.random.randint(255   ,				size=(3, 30, 400)   ,				dtype=np.uinta)]

             _lowerCamelCase				:  Optional[int]						=		[Image.fromarray(np.moveaxis(a__   ,				0   ,				-1)) for x in image_inputs]

             return image_inputs


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Union[str, Any]						=		SamProcessor(image_processor=self.get_image_processor())
             processor.save_pretrained(self.tmpdirname)

             _lowerCamelCase				:  List[Any]						=		self.get_image_processor(do_normalize=a__   ,				padding_value=1.0)

             _lowerCamelCase				:  Optional[int]						=		SamProcessor.from_pretrained(self.tmpdirname   ,				do_normalize=a__   ,				padding_value=1.0)

             self.assertEqual(processor.image_processor.to_json_string()   ,				image_processor_add_kwargs.to_json_string())
             self.assertIsInstance(processor.image_processor   ,				a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.get_image_processor()

             _lowerCamelCase				:  Union[str, Any]						=		SamProcessor(image_processor=a__)

             _lowerCamelCase				:  Tuple						=		self.prepare_image_inputs()

             _lowerCamelCase				:  List[str]						=		image_processor(a__   ,				return_tensors='''np''')
             _lowerCamelCase				:  Union[str, Any]						=		processor(images=a__   ,				return_tensors='''np''')

             input_feat_extract.pop('''original_sizes''')  # pop original_sizes as it is popped in the processor
             input_feat_extract.pop('''reshaped_input_sizes''')  # pop reshaped_input_sizes as it is popped in the processor

             for key in input_feat_extract.keys():
                    self.assertAlmostEqual(input_feat_extract[key].sum()   ,				input_processor[key].sum()   ,				delta=1e-2)



      @require_tf
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		self.get_image_processor()

             _lowerCamelCase				:  Optional[Any]						=		SamProcessor(image_processor=a__)
             _lowerCamelCase				:  Dict						=		[tf.ones((1, 3, 5, 5))]

             _lowerCamelCase				:  Optional[int]						=		[[1764, 2646]]

             _lowerCamelCase				:  Union[str, Any]						=		[[683, 1024]]
             _lowerCamelCase				:  Union[str, Any]						=		processor.post_process_masks(a__   ,				a__   ,				a__   ,				return_tensors='''tf''')
             self.assertEqual(masks[0].shape   ,				(1, 3, 1764, 2646))

             _lowerCamelCase				:  List[Any]						=		processor.post_process_masks(
                 a__   ,				tf.convert_to_tensor(a__)   ,				tf.convert_to_tensor(a__)   ,				return_tensors='''tf'''   ,				)
             self.assertEqual(masks[0].shape   ,				(1, 3, 1764, 2646))

             # should also work with np
             _lowerCamelCase				:  Optional[Any]						=		[np.ones((1, 3, 5, 5))]
             _lowerCamelCase				:  Union[str, Any]						=		processor.post_process_masks(
                 a__   ,				np.array(a__)   ,				np.array(a__)   ,				return_tensors='''tf''')

             self.assertEqual(masks[0].shape   ,				(1, 3, 1764, 2646))

             _lowerCamelCase				:  str						=		[[1, 0], [0, 1]]
             with self.assertRaises(tf.errors.InvalidArgumentError):
                    _lowerCamelCase				:  Optional[int]						=		processor.post_process_masks(
                        a__   ,				np.array(a__)   ,				np.array(a__)   ,				return_tensors='''tf''')







@require_vision
@require_torchvision
class       __A							(   unittest.TestCase	):




      """simple docstring"""







      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		tempfile.mkdtemp()
             _lowerCamelCase				:  Dict						=		SamImageProcessor()
             _lowerCamelCase				:  List[str]						=		SamProcessor(a__)
             processor.save_pretrained(self.tmpdirname)


      def 					__snake_case      (		self   ,				**a__):



             """simple docstring"""





             return AutoProcessor.from_pretrained(self.tmpdirname   ,				**a__).image_processor


      def 					__snake_case      (		self):



             """simple docstring"""





             shutil.rmtree(self.tmpdirname)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		[np.random.randint(255   ,				size=(3, 30, 400)   ,				dtype=np.uinta)]

             _lowerCamelCase				:  List[Any]						=		[Image.fromarray(np.moveaxis(a__   ,				0   ,				-1)) for x in image_inputs]

             return image_inputs


      @is_pt_tf_cross_test
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		self.get_image_processor()

             _lowerCamelCase				:  Dict						=		SamProcessor(image_processor=a__)
             _lowerCamelCase				:  Union[str, Any]						=		np.random.randint(0   ,				2   ,				size=(1, 3, 5, 5)).astype(np.floataa)
             _lowerCamelCase				:  str						=		[tf.convert_to_tensor(a__)]
             _lowerCamelCase				:  Tuple						=		[torch.tensor(a__)]

             _lowerCamelCase				:  Union[str, Any]						=		[[1764, 2646]]

             _lowerCamelCase				:  int						=		[[683, 1024]]
             _lowerCamelCase				:  Tuple						=		processor.post_process_masks(
                 a__   ,				a__   ,				a__   ,				return_tensors='''tf''')
             _lowerCamelCase				:  List[Any]						=		processor.post_process_masks(
                 a__   ,				a__   ,				a__   ,				return_tensors='''pt''')

             self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()))



      @is_pt_tf_cross_test
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Tuple						=		self.get_image_processor()

             _lowerCamelCase				:  Tuple						=		SamProcessor(image_processor=a__)

             _lowerCamelCase				:  List[str]						=		self.prepare_image_inputs()

             _lowerCamelCase				:  str						=		image_processor(a__   ,				return_tensors='''pt''')['''pixel_values'''].numpy()
             _lowerCamelCase				:  Dict						=		processor(images=a__   ,				return_tensors='''pt''')['''pixel_values'''].numpy()

             _lowerCamelCase				:  Union[str, Any]						=		image_processor(a__   ,				return_tensors='''tf''')['''pixel_values'''].numpy()
             _lowerCamelCase				:  List[Any]						=		processor(images=a__   ,				return_tensors='''tf''')['''pixel_values'''].numpy()

             self.assertTrue(np.allclose(a__   ,				a__))
             self.assertTrue(np.allclose(a__   ,				a__))
             self.assertTrue(np.allclose(a__   ,				a__))








import argparse

import torch

from transformers import GPTaLMHeadModel, RobertaForMaskedLM


if __name__ == "__main__":
       _lowerCamelCase      							=   argparse.ArgumentParser(
           description=(
               'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned'
               ' Distillation'
           )
       )
       parser.add_argument('--model_type', default='roberta', choices=['roberta', 'gpt2'])
       parser.add_argument('--model_name', default='roberta-large', type=str)
       parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_roberta_048131723.pth', type=str)
       parser.add_argument('--vocab_transform', action='store_true')
       _lowerCamelCase      							=   parser.parse_args()

       if args.model_type == "roberta":
              _lowerCamelCase      							=   RobertaForMaskedLM.from_pretrained(args.model_name)
              _lowerCamelCase      							=   'roberta'
       elif args.model_type == "gpt2":
              _lowerCamelCase      							=   GPTaLMHeadModel.from_pretrained(args.model_name)
              _lowerCamelCase      							=   'transformer'

       _lowerCamelCase      							=   model.state_dict()
       _lowerCamelCase      							=   {}

       # Embeddings #
       if args.model_type == "gpt2":
              for param_name in ["wte.weight", "wpe.weight"]:
                     _lowerCamelCase      							=   state_dict[F'''{prefix}.{param_name}''']
       else:
              for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]:
                     _lowerCamelCase      							=   F'''{prefix}.embeddings.{w}.weight'''
                     _lowerCamelCase      							=   state_dict[param_name]
              for w in ["weight", "bias"]:
                     _lowerCamelCase      							=   F'''{prefix}.embeddings.LayerNorm.{w}'''
                     _lowerCamelCase      							=   state_dict[param_name]

    # Transformer Blocks #
       _lowerCamelCase      							=   0
       for teacher_idx in [0, 2, 4, 7, 9, 11]:
              if args.model_type == "gpt2":
                     for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]:
                            for w in ["weight", "bias"]:
                                   _lowerCamelCase      							=   state_dict[
                                       F'''{prefix}.h.{teacher_idx}.{layer}.{w}'''
                                   ]
                     _lowerCamelCase      							=   state_dict[F'''{prefix}.h.{teacher_idx}.attn.bias''']
              else:
                     for layer in [
                         "attention.self.query",
                         "attention.self.key",
                         "attention.self.value",
                         "attention.output.dense",
                         "attention.output.LayerNorm",
                         "intermediate.dense",
                         "output.dense",
                         "output.LayerNorm",
                     ]:
                            for w in ["weight", "bias"]:
                                   _lowerCamelCase      							=   state_dict[
                                       F'''{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}'''
                                   ]
              std_idx += 1

       # Language Modeling Head ###s
       if args.model_type == "roberta":
              for layer in ["lm_head.decoder.weight", "lm_head.bias"]:
                     _lowerCamelCase      							=   state_dict[F'''{layer}''']
              if args.vocab_transform:
                     for w in ["weight", "bias"]:
                            _lowerCamelCase      							=   state_dict[F'''lm_head.dense.{w}''']
                            _lowerCamelCase      							=   state_dict[F'''lm_head.layer_norm.{w}''']
       elif args.model_type == "gpt2":
              for w in ["weight", "bias"]:
                     _lowerCamelCase      							=   state_dict[F'''{prefix}.ln_f.{w}''']
              _lowerCamelCase      							=   state_dict['lm_head.weight']

       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)

