

'''simple docstring'''





import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / """utils"""))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


UpperCamelCase_							=					get_tests_dir("""fixtures""")





class 		__SCREAMING_SNAKE_CASE       ( unittest.TestCase			):







				def    lowerCamelCase_  (					self    :		Optional[Any]      ):
										'''simple docstring'''
										lowercase   :       Optional[Any]								=mock.Mock()
										lowercase   :       List[Any]								=500
										lowercase   :       List[str]								={}
										lowercase   :       List[Any]								=HTTPError
										lowercase   :       Optional[int]								={}

										# Download this model to make sure it's in the cache.
										lowercase   :       Optional[int]								=ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit'''      )
										# Under the mock environment we get a 500 error when trying to reach the model.
										with mock.patch('''requests.Session.request'''		,				return_value=a_      ) as mock_head:
																lowercase   :       str								=ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit'''      )
																# This check we did call the fake head request
																mock_head.assert_called()







				def    lowerCamelCase_  (					self    :		Any      ):
										'''simple docstring'''
										lowercase   :       Optional[int]								=ViTImageProcessor.from_pretrained(
										    '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'''      )







				def    lowerCamelCase_  (					self    :		Dict      ):
										'''simple docstring'''



										with self.assertRaises(a_      ):
																# config is in subfolder, the following should not work without specifying the subfolder
																lowercase   :       Union[str, Any]								=AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants'''      )

										lowercase   :       Optional[Any]								=AutoImageProcessor.from_pretrained(
										    '''hf-internal-testing/stable-diffusion-all-variants'''		,				subfolder='''feature_extractor'''      )

										self.assertIsNotNone(a_      )





@is_staging_test
class 		__SCREAMING_SNAKE_CASE       ( unittest.TestCase			):







				@classmethod
				def    lowerCamelCase_  (					cls    :		Dict      ):
										'''simple docstring'''
										lowercase   :       Union[str, Any]								=TOKEN
										HfFolder.save_token(a_      )







				@classmethod
				def    lowerCamelCase_  (					cls    :		Optional[int]      ):
										'''simple docstring'''



										try:
																delete_repo(token=cls._token		,				repo_id='''test-image-processor'''      )
										except HTTPError:
																pass

										try:
																delete_repo(token=cls._token		,				repo_id='''valid_org/test-image-processor-org'''      )
										except HTTPError:
																pass

										try:
																delete_repo(token=cls._token		,				repo_id='''test-dynamic-image-processor'''      )
										except HTTPError:
																pass







				def    lowerCamelCase_  (					self    :		List[str]      ):
										'''simple docstring'''
										lowercase   :       Union[str, Any]								=ViTImageProcessor.from_pretrained(a_      )
										image_processor.push_to_hub('''test-image-processor'''		,				use_auth_token=self._token      )

										lowercase   :       Tuple								=ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor'''      )
										for k, v in image_processor.__dict__.items():
																self.assertEqual(a_		,				getattr(a_		,				a_      )      )

										# Reset repo
										delete_repo(token=self._token		,				repo_id='''test-image-processor'''      )

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
																image_processor.save_pretrained(
																    a_		,				repo_id='''test-image-processor'''		,				push_to_hub=a_		,				use_auth_token=self._token      )

										lowercase   :       Optional[Any]								=ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor'''      )
										for k, v in image_processor.__dict__.items():
																self.assertEqual(a_		,				getattr(a_		,				a_      )      )







				def    lowerCamelCase_  (					self    :		Optional[int]      ):
										'''simple docstring'''
										lowercase   :       Optional[int]								=ViTImageProcessor.from_pretrained(a_      )
										image_processor.push_to_hub('''valid_org/test-image-processor'''		,				use_auth_token=self._token      )

										lowercase   :       Union[str, Any]								=ViTImageProcessor.from_pretrained('''valid_org/test-image-processor'''      )
										for k, v in image_processor.__dict__.items():
																self.assertEqual(a_		,				getattr(a_		,				a_      )      )

										# Reset repo
										delete_repo(token=self._token		,				repo_id='''valid_org/test-image-processor'''      )

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
																image_processor.save_pretrained(
																    a_		,				repo_id='''valid_org/test-image-processor-org'''		,				push_to_hub=a_		,				use_auth_token=self._token      )

										lowercase   :       List[Any]								=ViTImageProcessor.from_pretrained('''valid_org/test-image-processor-org'''      )
										for k, v in image_processor.__dict__.items():
																self.assertEqual(a_		,				getattr(a_		,				a_      )      )







				def    lowerCamelCase_  (					self    :		str      ):
										'''simple docstring'''
										CustomImageProcessor.register_for_auto_class()
										lowercase   :       List[str]								=CustomImageProcessor.from_pretrained(a_      )

										image_processor.push_to_hub('''test-dynamic-image-processor'''		,				use_auth_token=self._token      )

										# This has added the proper auto_map field to the config
										self.assertDictEqual(
										    image_processor.auto_map		,				{'''AutoImageProcessor''': '''custom_image_processing.CustomImageProcessor'''}		,				)

										lowercase   :       Optional[int]								=AutoImageProcessor.from_pretrained(
										    F'''{USER}/test-dynamic-image-processor'''		,				trust_remote_code=a_      )
										# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
										self.assertEqual(new_image_processor.__class__.__name__		,				'''CustomImageProcessor'''      )



'''simple docstring'''





import argparse

import torch

from transformers import GPTaLMHeadModel, RobertaForMaskedLM


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

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

							UpperCamelCase_							=					model.state_dict()
							UpperCamelCase_							=					{}

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

    # Transformer Blocks #
							UpperCamelCase_							=					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"]:
																																			UpperCamelCase_							=					state_dict[
																																			    f'''{prefix}.h.{teacher_idx}.{layer}.{w}'''
																																			]
																					UpperCamelCase_							=					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"]:
																																			UpperCamelCase_							=					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"]:
																					UpperCamelCase_							=					state_dict[f'''{layer}''']
														if args.vocab_transform:
																					for w in ["weight", "bias"]:
																												UpperCamelCase_							=					state_dict[f'''lm_head.dense.{w}''']
																												UpperCamelCase_							=					state_dict[f'''lm_head.layer_norm.{w}''']
							elif args.model_type == "gpt2":
														for w in ["weight", "bias"]:
																					UpperCamelCase_							=					state_dict[f'''{prefix}.ln_f.{w}''']
														UpperCamelCase_							=					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)





