import argparse

import requests
import torch
from PIL import Image

from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor






def        __UpperCAmelCase    (       UpperCAmelCase       )->       List[str]:



			"""simple docstring"""







			if "cls_token" in name:
						lowercase							=		name.replace('''cls_token''',		'''vit.embeddings.cls_token'''       )
			if "mask_token" in name:
						lowercase							=		name.replace('''mask_token''',		'''decoder.mask_token'''       )
			if "decoder_pos_embed" in name:
						lowercase							=		name.replace('''decoder_pos_embed''',		'''decoder.decoder_pos_embed'''       )
			if "pos_embed" in name and "decoder" not in name:
						lowercase							=		name.replace('''pos_embed''',		'''vit.embeddings.position_embeddings'''       )
			if "patch_embed.proj" in name:
						lowercase							=		name.replace('''patch_embed.proj''',		'''vit.embeddings.patch_embeddings.projection'''       )
			if "patch_embed.norm" in name:
						lowercase							=		name.replace('''patch_embed.norm''',		'''vit.embeddings.norm'''       )
			if "decoder_blocks" in name:
						lowercase							=		name.replace('''decoder_blocks''',		'''decoder.decoder_layers'''       )
			if "blocks" in name:
						lowercase							=		name.replace('''blocks''',		'''vit.encoder.layer'''       )
			if "attn.proj" in name:
						lowercase							=		name.replace('''attn.proj''',		'''attention.output.dense'''       )
			if "attn" in name:
						lowercase							=		name.replace('''attn''',		'''attention.self'''       )
			if "norm1" in name:
						lowercase							=		name.replace('''norm1''',		'''layernorm_before'''       )
			if "norm2" in name:
						lowercase							=		name.replace('''norm2''',		'''layernorm_after'''       )
			if "mlp.fc1" in name:
						lowercase							=		name.replace('''mlp.fc1''',		'''intermediate.dense'''       )
			if "mlp.fc2" in name:
						lowercase							=		name.replace('''mlp.fc2''',		'''output.dense'''       )
			if "decoder_embed" in name:
						lowercase							=		name.replace('''decoder_embed''',		'''decoder.decoder_embed'''       )
			if "decoder_norm" in name:
						lowercase							=		name.replace('''decoder_norm''',		'''decoder.decoder_norm'''       )
			if "decoder_pred" in name:
						lowercase							=		name.replace('''decoder_pred''',		'''decoder.decoder_pred'''       )
			if "norm.weight" in name and "decoder" not in name:
						lowercase							=		name.replace('''norm.weight''',		'''vit.layernorm.weight'''       )
			if "norm.bias" in name and "decoder" not in name:
						lowercase							=		name.replace('''norm.bias''',		'''vit.layernorm.bias'''       )

			return name






def        __UpperCAmelCase    (       UpperCAmelCase,		UpperCAmelCase       )->       Union[str, Any]:



			"""simple docstring"""







			for key in orig_state_dict.copy().keys():
						lowercase							=		orig_state_dict.pop(UpperCAmelCase       )

						if "qkv" in key:
									lowercase							=		key.split('''.'''       )
									lowercase							=		int(key_split[1]       )
									if "decoder_blocks" in key:
												lowercase							=		config.decoder_hidden_size
												lowercase							=		'''decoder.decoder_layers.'''
												if "weight" in key:
															lowercase							=		val[:dim, :]
															lowercase							=		val[dim : dim * 2, :]
															lowercase							=		val[-dim:, :]
												elif "bias" in key:
															lowercase							=		val[:dim]
															lowercase							=		val[dim : dim * 2]
															lowercase							=		val[-dim:]
									else:
												lowercase							=		config.hidden_size
												lowercase							=		'''vit.encoder.layer.'''
												if "weight" in key:
															lowercase							=		val[:dim, :]
															lowercase							=		val[dim : dim * 2, :]
															lowercase							=		val[-dim:, :]
												elif "bias" in key:
															lowercase							=		val[:dim]
															lowercase							=		val[dim : dim * 2]
															lowercase							=		val[-dim:]

						else:
									lowercase							=		val

			return orig_state_dict






def        __UpperCAmelCase    (       UpperCAmelCase,		UpperCAmelCase       )->       List[Any]:



			"""simple docstring"""







			lowercase							=		ViTMAEConfig()
			if "large" in checkpoint_url:
						lowercase							=		1024
						lowercase							=		4096
						lowercase							=		24
						lowercase							=		16
			elif "huge" in checkpoint_url:
						lowercase							=		14
						lowercase							=		1280
						lowercase							=		5120
						lowercase							=		32
						lowercase							=		16

			lowercase							=		ViTMAEForPreTraining(UpperCAmelCase       )

			lowercase							=		torch.hub.load_state_dict_from_url(UpperCAmelCase,		map_location='''cpu'''       )['''model''']

			lowercase							=		ViTMAEImageProcessor(size=config.image_size       )

			lowercase							=		convert_state_dict(UpperCAmelCase,		UpperCAmelCase       )

			model.load_state_dict(UpperCAmelCase       )
			model.eval()

			lowercase							=		'''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg'''

			lowercase							=		Image.open(requests.get(UpperCAmelCase,		stream=UpperCAmelCase       ).raw       )
			lowercase							=		ViTMAEImageProcessor(size=config.image_size       )
			lowercase							=		image_processor(images=UpperCAmelCase,		return_tensors='''pt'''       )

			# forward pass
			torch.manual_seed(2       )
			lowercase							=		model(**UpperCAmelCase       )
			lowercase							=		outputs.logits

			if "large" in checkpoint_url:
						lowercase							=		torch.tensor(
						    [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]]       )
			elif "huge" in checkpoint_url:
						lowercase							=		torch.tensor(
						    [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]]       )
			else:
						lowercase							=		torch.tensor(
						    [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]]       )

			# verify logits
			assert torch.allclose(logits[0, :3, :3],		UpperCAmelCase,		atol=1e-4       )

			print(f'Saving model to {pytorch_dump_folder_path}'       )
			model.save_pretrained(UpperCAmelCase       )

			print(f'Saving image processor to {pytorch_dump_folder_path}'       )
			image_processor.save_pretrained(UpperCAmelCase       )


if __name__ == "__main__":
						A_      =      argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    "--checkpoint_url",
						    default="https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth",
						    type=str,
						    help="URL of the checkpoint you'd like to convert.",
						)
						parser.add_argument(
						    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
						)

						A_      =      parser.parse_args()
						convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)






import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import datasets
import datasets.config

from .utils import require_beam






class      __lowercase					(    datasets.BeamBasedBuilder    ):

						def        __a		(	self				:      Tuple   )							->		Tuple:


									'''simple docstring'''

									return datasets.DatasetInfo(
									    features=datasets.Features({'''content''': datasets.Value('''string'''   )}   )							,							supervised_keys=__lowerCamelCase							,							)

						def        __a		(	self				:      Union[str, Any]							,							__lowerCamelCase				:      Union[str, Any]							,							__lowerCamelCase				:      Tuple   )							->		int:


									'''simple docstring'''

									return [datasets.SplitGenerator(name=datasets.Split.TRAIN							,							gen_kwargs={'''examples''': get_test_dummy_examples()}   )]



						def        __a		(	self				:      List[Any]							,							__lowerCamelCase				:      Any							,							__lowerCamelCase				:      Union[str, Any]   )							->		Optional[int]:


									'''simple docstring'''

									import apache_beam as beam

									return pipeline | "Load Examples" >> beam.Create(__lowerCamelCase   )






class      __lowercase					(    datasets.BeamBasedBuilder    ):

						def        __a		(	self				:      int   )							->		Any:


									'''simple docstring'''

									return datasets.DatasetInfo(
									    features=datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string'''   )}   )}   )							,							supervised_keys=__lowerCamelCase							,							)

						def        __a		(	self				:      Optional[int]							,							__lowerCamelCase				:      List[Any]							,							__lowerCamelCase				:      Optional[int]   )							->		int:


									'''simple docstring'''

									return [
									    datasets.SplitGenerator(name=datasets.Split.TRAIN							,							gen_kwargs={'''examples''': get_test_nested_examples()}   )
									]



						def        __a		(	self				:      Union[str, Any]							,							__lowerCamelCase				:      Tuple							,							__lowerCamelCase				:      Union[str, Any]   )							->		Tuple:


									'''simple docstring'''

									import apache_beam as beam

									return pipeline | "Load Examples" >> beam.Create(__lowerCamelCase   )






def        __UpperCAmelCase    (       )->       Dict:



			"""simple docstring"""







			return [(i, {"content": content}) for i, content in enumerate(['''foo''', '''bar''', '''foobar''']       )]






def        __UpperCAmelCase    (       )->       List[str]:



			"""simple docstring"""







			return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['''foo''', '''bar''', '''foobar''']       )]






class      __lowercase					(    _A    ):

						@require_beam
						def        __a		(	self				:      Optional[int]   )							->		Optional[Any]:


									'''simple docstring'''

									lowercase							=		len(get_test_dummy_examples()   )
									with tempfile.TemporaryDirectory() as tmp_cache_dir:
												lowercase							=		DummyBeamDataset(cache_dir=__lowerCamelCase							,							beam_runner='''DirectRunner'''   )
												builder.download_and_prepare()
												self.assertTrue(
												    os.path.exists(
												        os.path.join(__lowerCamelCase							,							builder.name							,							'''default'''							,							'''0.0.0'''							,							f'{builder.name}-train.arrow'   )   )   )
												self.assertDictEqual(builder.info.features							,							datasets.Features({'''content''': datasets.Value('''string'''   )}   )   )
												lowercase							=		builder.as_dataset()
												self.assertEqual(dset['''train'''].num_rows							,							__lowerCamelCase   )
												self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples							,							__lowerCamelCase   )
												self.assertDictEqual(dset['''train'''][0]							,							get_test_dummy_examples()[0][1]   )
												self.assertDictEqual(
												    dset['''train'''][expected_num_examples - 1]							,							get_test_dummy_examples()[expected_num_examples - 1][1]   )
												self.assertTrue(
												    os.path.exists(os.path.join(__lowerCamelCase							,							builder.name							,							'''default'''							,							'''0.0.0'''							,							'''dataset_info.json'''   )   )   )
												del dset

						@require_beam
						def        __a		(	self				:      Union[str, Any]   )							->		List[Any]:


									'''simple docstring'''

									import apache_beam as beam

									lowercase							=		beam.io.parquetio.WriteToParquet

									lowercase							=		len(get_test_dummy_examples()   )
									with tempfile.TemporaryDirectory() as tmp_cache_dir:
												lowercase							=		DummyBeamDataset(cache_dir=__lowerCamelCase							,							beam_runner='''DirectRunner'''   )
												with patch('''apache_beam.io.parquetio.WriteToParquet'''   ) as write_parquet_mock:
															lowercase							=		partial(__lowerCamelCase							,							num_shards=2   )
															builder.download_and_prepare()
												self.assertTrue(
												    os.path.exists(
												        os.path.join(
												            __lowerCamelCase							,							builder.name							,							'''default'''							,							'''0.0.0'''							,							f'{builder.name}-train-00000-of-00002.arrow'   )   )   )
												self.assertTrue(
												    os.path.exists(
												        os.path.join(
												            __lowerCamelCase							,							builder.name							,							'''default'''							,							'''0.0.0'''							,							f'{builder.name}-train-00000-of-00002.arrow'   )   )   )
												self.assertDictEqual(builder.info.features							,							datasets.Features({'''content''': datasets.Value('''string'''   )}   )   )
												lowercase							=		builder.as_dataset()
												self.assertEqual(dset['''train'''].num_rows							,							__lowerCamelCase   )
												self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples							,							__lowerCamelCase   )
												# Order is not preserved when sharding, so we just check that all the elements are there
												self.assertListEqual(sorted(dset['''train''']['''content''']   )							,							sorted(['''foo''', '''bar''', '''foobar''']   )   )
												self.assertTrue(
												    os.path.exists(os.path.join(__lowerCamelCase							,							builder.name							,							'''default'''							,							'''0.0.0'''							,							'''dataset_info.json'''   )   )   )
												del dset

						@require_beam
						def        __a		(	self				:      int   )							->		int:


									'''simple docstring'''

									with tempfile.TemporaryDirectory() as tmp_cache_dir:
												lowercase							=		DummyBeamDataset(cache_dir=__lowerCamelCase   )
												self.assertRaises(datasets.builder.MissingBeamOptions							,							builder.download_and_prepare   )



						@require_beam
						def        __a		(	self				:      str   )							->		List[Any]:


									'''simple docstring'''

									lowercase							=		len(get_test_nested_examples()   )
									with tempfile.TemporaryDirectory() as tmp_cache_dir:
												lowercase							=		NestedBeamDataset(cache_dir=__lowerCamelCase							,							beam_runner='''DirectRunner'''   )
												builder.download_and_prepare()
												self.assertTrue(
												    os.path.exists(
												        os.path.join(__lowerCamelCase							,							builder.name							,							'''default'''							,							'''0.0.0'''							,							f'{builder.name}-train.arrow'   )   )   )
												self.assertDictEqual(
												    builder.info.features							,							datasets.Features({'''a''': datasets.Sequence({'''b''': datasets.Value('''string'''   )}   )}   )   )
												lowercase							=		builder.as_dataset()
												self.assertEqual(dset['''train'''].num_rows							,							__lowerCamelCase   )
												self.assertEqual(dset['''train'''].info.splits['''train'''].num_examples							,							__lowerCamelCase   )
												self.assertDictEqual(dset['''train'''][0]							,							get_test_nested_examples()[0][1]   )
												self.assertDictEqual(
												    dset['''train'''][expected_num_examples - 1]							,							get_test_nested_examples()[expected_num_examples - 1][1]   )
												self.assertTrue(
												    os.path.exists(os.path.join(__lowerCamelCase							,							builder.name							,							'''default'''							,							'''0.0.0'''							,							'''dataset_info.json'''   )   )   )
												del dset





