





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   ):



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



       def 			A				(  self						: Optional[Any]       ,      **UpperCAmelCase						: Dict      ):
           return AutoProcessor.from_pretrained(self.tmpdirname       ,      **a__      ).image_processor



       def 			A				(  self						: Any      ):
           shutil.rmtree(self.tmpdirname      )



       def 			A				(  self						: Dict      ):
           lowerCAmelCase_       :						Optional[Any]							= [np.random.randint(2_55       ,      size=(3, 30, 4_00)       ,      dtype=np.uinta      )]

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

           return image_inputs



       def 			A				(  self						: int      ):
           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 			A				(  self						: List[Any]      ):
           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 			A				(  self						: Optional[Any]      ):
           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							= [[17_64, 26_46]]

           lowerCAmelCase_       :						Optional[Any]							= [[6_83, 10_24]]
           lowerCAmelCase_       :						List[Any]							= processor.post_process_masks(a__       ,      a__       ,      a__      )
           self.assertEqual(masks[0].shape       ,      (1, 3, 17_64, 26_46)      )

           lowerCAmelCase_       :						str							= processor.post_process_masks(
               a__       ,      torch.tensor(a__      )       ,      torch.tensor(a__      )      )
           self.assertEqual(masks[0].shape       ,      (1, 3, 17_64, 26_46)      )

           # 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, 17_64, 26_46)      )

           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   ):



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



       def 			A				(  self						: Any       ,      **UpperCAmelCase						: Dict      ):
           return AutoProcessor.from_pretrained(self.tmpdirname       ,      **a__      ).image_processor



       def 			A				(  self						: Optional[int]      ):
           shutil.rmtree(self.tmpdirname      )



       def 			A				(  self						: List[str]      ):
           lowerCAmelCase_       :						Tuple							= [np.random.randint(2_55       ,      size=(3, 30, 4_00)       ,      dtype=np.uinta      )]

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

           return image_inputs



       def 			A				(  self						: List[str]      ):
           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 			A				(  self						: Optional[int]      ):
           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 			A				(  self						: List[Any]      ):
           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]							= [[17_64, 26_46]]

           lowerCAmelCase_       :						Union[str, Any]							= [[6_83, 10_24]]
           lowerCAmelCase_       :						Union[str, Any]							= processor.post_process_masks(a__       ,      a__       ,      a__       ,      return_tensors="""tf"""      )
           self.assertEqual(masks[0].shape       ,      (1, 3, 17_64, 26_46)      )

           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, 17_64, 26_46)      )

           # 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, 17_64, 26_46)      )

           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   ):



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



       def 			A				(  self						: List[str]       ,      **UpperCAmelCase						: Union[str, Any]      ):
           return AutoProcessor.from_pretrained(self.tmpdirname       ,      **a__      ).image_processor



       def 			A				(  self						: Optional[Any]      ):
           shutil.rmtree(self.tmpdirname      )



       def 			A				(  self						: List[str]      ):
           lowerCAmelCase_       :						List[Any]							= [np.random.randint(2_55       ,      size=(3, 30, 4_00)       ,      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 			A				(  self						: List[str]      ):
           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]							= [[17_64, 26_46]]

           lowerCAmelCase_       :						int							= [[6_83, 10_24]]
           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 			A				(  self						: Optional[int]      ):
           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)

