






import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


_A     :      List[Any]   					=logging.get_logger(__name__)

_A     :      Dict   					={'''vocab_file''': '''spiece.model'''}

_A     :      Dict   					={
    '''vocab_file''': {
        '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''',
        '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''',
    }
}

_A     :      int   					={
    '''xlnet-base-cased''': None,
    '''xlnet-large-cased''': None,
}

# Segments (not really needed)
_A     :      Any   					=0
_A     :      str   					=1
_A     :      Tuple   					=2
_A     :      Optional[Any]   					=3
_A     :      Optional[Any]   					=4

class _lowercase     (    _lowercase		):
							a    				=	VOCAB_FILES_NAMES
							a    				=	PRETRAINED_VOCAB_FILES_MAP
							a    				=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							a    				=	"""left"""




							def __init__(							self:    Tuple      ,							UpperCamelCase__:    Optional[int]      ,							UpperCamelCase__:    str=False      ,							UpperCamelCase__:    str=True      ,							UpperCamelCase__:    Dict=False      ,							UpperCamelCase__:    Dict="<s>"      ,							UpperCamelCase__:    int="</s>"      ,							UpperCamelCase__:    str="<unk>"      ,							UpperCamelCase__:    int="<sep>"      ,							UpperCamelCase__:    int="<pad>"      ,							UpperCamelCase__:    Any="<cls>"      ,							UpperCamelCase__:    Optional[Any]="<mask>"      ,							UpperCamelCase__:    Tuple=["<eop>", "<eod>"]      ,							UpperCamelCase__:    Optional[Dict[str, Any]] = None      ,							**UpperCamelCase__:    str      ,							):
														# Mask token behave like a normal word, i.e. include the space before it
														lowerCamelCase__ :     List[Any]	  =	AddedToken(UpperCamelCase__      ,							lstrip=UpperCamelCase__      ,							rstrip=UpperCamelCase__					) if isinstance(UpperCamelCase__      ,							UpperCamelCase__					) else mask_token

														lowerCamelCase__ :     List[Any]	  =	{} if sp_model_kwargs is None else sp_model_kwargs

														super().__init__(
														    do_lower_case=UpperCamelCase__      ,							remove_space=UpperCamelCase__      ,							keep_accents=UpperCamelCase__      ,							bos_token=UpperCamelCase__      ,							eos_token=UpperCamelCase__      ,							unk_token=UpperCamelCase__      ,							sep_token=UpperCamelCase__      ,							pad_token=UpperCamelCase__      ,							cls_token=UpperCamelCase__      ,							mask_token=UpperCamelCase__      ,							additional_special_tokens=UpperCamelCase__      ,							sp_model_kwargs=self.sp_model_kwargs      ,							**UpperCamelCase__      ,							)

														lowerCamelCase__ :     Optional[int]	  =	3

														lowerCamelCase__ :     Optional[int]	  =	do_lower_case
														lowerCamelCase__ :     Union[str, Any]	  =	remove_space
														lowerCamelCase__ :     str	  =	keep_accents
														lowerCamelCase__ :     Optional[Any]	  =	vocab_file

														lowerCamelCase__ :     Dict	  =	spm.SentencePieceProcessor(**self.sp_model_kwargs					)
														self.sp_model.Load(UpperCamelCase__					)




							@property
							def 		lowerCamelCase_    (							self:    Any					):
														return len(self.sp_model					)




							def 		lowerCamelCase_    (							self:    Tuple					):
														lowerCamelCase__ :     List[Any]	  =	{self.convert_ids_to_tokens(UpperCamelCase__					): i for i in range(self.vocab_size					)}
														vocab.update(self.added_tokens_encoder					)
														return vocab




							def __getstate__(							self:    List[Any]					):
														lowerCamelCase__ :     List[str]	  =	self.__dict__.copy()
														lowerCamelCase__ :     List[str]	  =	None
														return state




							def __setstate__(							self:    List[Any]      ,							UpperCamelCase__:    Optional[Any]					):
														lowerCamelCase__ :     Tuple	  =	d

														# for backward compatibility
														if not hasattr(self      ,							"""sp_model_kwargs"""					):
																					lowerCamelCase__ :     str	  =	{}

														lowerCamelCase__ :     Dict	  =	spm.SentencePieceProcessor(**self.sp_model_kwargs					)
														self.sp_model.Load(self.vocab_file					)




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    Any					):
														if self.remove_space:
																					lowerCamelCase__ :     Any	  =	""" """.join(inputs.strip().split()					)
														else:
																					lowerCamelCase__ :     List[str]	  =	inputs
														lowerCamelCase__ :     Tuple	  =	outputs.replace("""``"""      ,							"""\""""					).replace("""''"""      ,							"""\""""					)

														if not self.keep_accents:
																					lowerCamelCase__ :     Dict	  =	unicodedata.normalize("""NFKD"""      ,							UpperCamelCase__					)
																					lowerCamelCase__ :     Optional[Any]	  =	"""""".join([c for c in outputs if not unicodedata.combining(UpperCamelCase__					)]					)
														if self.do_lower_case:
																					lowerCamelCase__ :     str	  =	outputs.lower()

														return outputs




							def 		lowerCamelCase_    (							self:    str      ,							UpperCamelCase__:    str					):
														lowerCamelCase__ :     Optional[int]	  =	self.preprocess_text(UpperCamelCase__					)
														lowerCamelCase__ :     Optional[Any]	  =	self.sp_model.encode(UpperCamelCase__      ,							out_type=UpperCamelCase__					)
														lowerCamelCase__ :     Optional[int]	  =	[]
														for piece in pieces:
																					if len(UpperCamelCase__					) > 1 and piece[-1] == str(""","""					) and piece[-2].isdigit():
																												lowerCamelCase__ :     Any	  =	self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase__      ,							""""""					)					)
																												if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
																																			if len(cur_pieces[0]					) == 1:
																																										lowerCamelCase__ :     int	  =	cur_pieces[1:]
																																			else:
																																										lowerCamelCase__ :     List[str]	  =	cur_pieces[0][1:]
																												cur_pieces.append(piece[-1]					)
																												new_pieces.extend(UpperCamelCase__					)
																					else:
																												new_pieces.append(UpperCamelCase__					)

														return new_pieces




							def 		lowerCamelCase_    (							self:    Dict      ,							UpperCamelCase__:    str					):
														return self.sp_model.PieceToId(UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Dict      ,							UpperCamelCase__:    Union[str, Any]					):
														return self.sp_model.IdToPiece(UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Union[str, Any]      ,							UpperCamelCase__:    Union[str, Any]					):
														lowerCamelCase__ :     Optional[int]	  =	"""""".join(UpperCamelCase__					).replace(UpperCamelCase__      ,							""" """					).strip()
														return out_string




							def 		lowerCamelCase_    (							self:    List[str]      ,							UpperCamelCase__:    List[int]      ,							UpperCamelCase__:    bool = False      ,							UpperCamelCase__:    bool = None      ,							UpperCamelCase__:    bool = True      ,							**UpperCamelCase__:    Optional[Any]      ,							):
														lowerCamelCase__ :     Tuple	  =	kwargs.pop("""use_source_tokenizer"""      ,							UpperCamelCase__					)

														lowerCamelCase__ :     List[Any]	  =	self.convert_ids_to_tokens(UpperCamelCase__      ,							skip_special_tokens=UpperCamelCase__					)

														# To avoid mixing byte-level and unicode for byte-level BPT
														# we need to build string separately for added tokens and byte-level tokens
														# cf. https://github.com/huggingface/transformers/issues/1133
														lowerCamelCase__ :     Tuple	  =	[]
														lowerCamelCase__ :     Optional[Any]	  =	[]
														for token in filtered_tokens:
																					if skip_special_tokens and token in self.all_special_ids:
																												continue
																					if token in self.added_tokens_encoder:
																												if current_sub_text:
																																			sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__					)					)
																																			lowerCamelCase__ :     Optional[Any]	  =	[]
																												sub_texts.append(UpperCamelCase__					)
																					else:
																												current_sub_text.append(UpperCamelCase__					)
														if current_sub_text:
																					sub_texts.append(self.convert_tokens_to_string(UpperCamelCase__					)					)

														# Mimic the behavior of the Rust tokenizer:
														# By default, there are no spaces between special tokens
														lowerCamelCase__ :     int	  =	"""""".join(UpperCamelCase__					)

														lowerCamelCase__ :     Tuple	  =	(
														    clean_up_tokenization_spaces
														    if clean_up_tokenization_spaces is not None
														    else self.clean_up_tokenization_spaces
														)
														if clean_up_tokenization_spaces:
																					lowerCamelCase__ :     Optional[Any]	  =	self.clean_up_tokenization(UpperCamelCase__					)
																					return clean_text
														else:
																					return text




							def 		lowerCamelCase_    (							self:    Optional[int]      ,							UpperCamelCase__:    List[int]      ,							UpperCamelCase__:    Optional[List[int]] = None					):
														lowerCamelCase__ :     List[Any]	  =	[self.sep_token_id]
														lowerCamelCase__ :     List[Any]	  =	[self.cls_token_id]
														if token_ids_a is None:
																					return token_ids_a + sep + cls
														return token_ids_a + sep + token_ids_a + sep + cls




							def 		lowerCamelCase_    (							self:    int      ,							UpperCamelCase__:    List[int]      ,							UpperCamelCase__:    Optional[List[int]] = None      ,							UpperCamelCase__:    bool = False					):

														if already_has_special_tokens:
																					return super().get_special_tokens_mask(
																					    token_ids_a=UpperCamelCase__      ,							token_ids_a=UpperCamelCase__      ,							already_has_special_tokens=UpperCamelCase__					)

														if token_ids_a is not None:
																					return ([0] * len(UpperCamelCase__					)) + [1] + ([0] * len(UpperCamelCase__					)) + [1, 1]
														return ([0] * len(UpperCamelCase__					)) + [1, 1]




							def 		lowerCamelCase_    (							self:    List[Any]      ,							UpperCamelCase__:    List[int]      ,							UpperCamelCase__:    Optional[List[int]] = None					):
														lowerCamelCase__ :     Any	  =	[self.sep_token_id]
														lowerCamelCase__ :     str	  =	[2]

														if token_ids_a is None:
																					return len(token_ids_a + sep					) * [0] + cls_segment_id
														return len(token_ids_a + sep					) * [0] + len(token_ids_a + sep					) * [1] + cls_segment_id




							def 		lowerCamelCase_    (							self:    List[Any]      ,							UpperCamelCase__:    str      ,							UpperCamelCase__:    Optional[str] = None					):
														if not os.path.isdir(UpperCamelCase__					):
																					logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''					)
																					return
														lowerCamelCase__ :     Optional[Any]	  =	os.path.join(
														    UpperCamelCase__      ,							(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]					)

														if os.path.abspath(self.vocab_file					) != os.path.abspath(UpperCamelCase__					) and os.path.isfile(self.vocab_file					):
																					copyfile(self.vocab_file      ,							UpperCamelCase__					)
														elif not os.path.isfile(self.vocab_file					):
																					with open(UpperCamelCase__      ,							"""wb"""					) as fi:
																												lowerCamelCase__ :     List[Any]	  =	self.sp_model.serialized_model_proto()
																												fi.write(UpperCamelCase__					)

														return (out_vocab_file,)









'''simple docstring'''







import argparse

import requests
import torch
from PIL import Image

from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase				)				->	List[Any]:
							if "cls_token" in name:
														lowerCamelCase__ :     Any	  =	name.replace("""cls_token"""    ,      """vit.embeddings.cls_token"""				)
							if "mask_token" in name:
														lowerCamelCase__ :     Union[str, Any]	  =	name.replace("""mask_token"""    ,      """decoder.mask_token"""				)
							if "decoder_pos_embed" in name:
														lowerCamelCase__ :     Tuple	  =	name.replace("""decoder_pos_embed"""    ,      """decoder.decoder_pos_embed"""				)
							if "pos_embed" in name and "decoder" not in name:
														lowerCamelCase__ :     str	  =	name.replace("""pos_embed"""    ,      """vit.embeddings.position_embeddings"""				)
							if "patch_embed.proj" in name:
														lowerCamelCase__ :     Optional[int]	  =	name.replace("""patch_embed.proj"""    ,      """vit.embeddings.patch_embeddings.projection"""				)
							if "patch_embed.norm" in name:
														lowerCamelCase__ :     Any	  =	name.replace("""patch_embed.norm"""    ,      """vit.embeddings.norm"""				)
							if "decoder_blocks" in name:
														lowerCamelCase__ :     Dict	  =	name.replace("""decoder_blocks"""    ,      """decoder.decoder_layers"""				)
							if "blocks" in name:
														lowerCamelCase__ :     Union[str, Any]	  =	name.replace("""blocks"""    ,      """vit.encoder.layer"""				)
							if "attn.proj" in name:
														lowerCamelCase__ :     List[Any]	  =	name.replace("""attn.proj"""    ,      """attention.output.dense"""				)
							if "attn" in name:
														lowerCamelCase__ :     List[str]	  =	name.replace("""attn"""    ,      """attention.self"""				)
							if "norm1" in name:
														lowerCamelCase__ :     Any	  =	name.replace("""norm1"""    ,      """layernorm_before"""				)
							if "norm2" in name:
														lowerCamelCase__ :     Dict	  =	name.replace("""norm2"""    ,      """layernorm_after"""				)
							if "mlp.fc1" in name:
														lowerCamelCase__ :     str	  =	name.replace("""mlp.fc1"""    ,      """intermediate.dense"""				)
							if "mlp.fc2" in name:
														lowerCamelCase__ :     Union[str, Any]	  =	name.replace("""mlp.fc2"""    ,      """output.dense"""				)
							if "decoder_embed" in name:
														lowerCamelCase__ :     Tuple	  =	name.replace("""decoder_embed"""    ,      """decoder.decoder_embed"""				)
							if "decoder_norm" in name:
														lowerCamelCase__ :     Optional[int]	  =	name.replace("""decoder_norm"""    ,      """decoder.decoder_norm"""				)
							if "decoder_pred" in name:
														lowerCamelCase__ :     int	  =	name.replace("""decoder_pred"""    ,      """decoder.decoder_pred"""				)
							if "norm.weight" in name and "decoder" not in name:
														lowerCamelCase__ :     Union[str, Any]	  =	name.replace("""norm.weight"""    ,      """vit.layernorm.weight"""				)
							if "norm.bias" in name and "decoder" not in name:
														lowerCamelCase__ :     Dict	  =	name.replace("""norm.bias"""    ,      """vit.layernorm.bias"""				)

							return name





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	Tuple:
							for key in orig_state_dict.copy().keys():
														lowerCamelCase__ :     List[str]	  =	orig_state_dict.pop(UpperCamelCase				)

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

														else:
																					lowerCamelCase__ :     int	  =	val

							return orig_state_dict





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	int:
							lowerCamelCase__ :     Any	  =	ViTMAEConfig()
							if "large" in checkpoint_url:
														lowerCamelCase__ :     Any	  =	1024
														lowerCamelCase__ :     Optional[Any]	  =	4096
														lowerCamelCase__ :     List[str]	  =	24
														lowerCamelCase__ :     Union[str, Any]	  =	16
							elif "huge" in checkpoint_url:
														lowerCamelCase__ :     List[str]	  =	14
														lowerCamelCase__ :     Dict	  =	1280
														lowerCamelCase__ :     Tuple	  =	5120
														lowerCamelCase__ :     List[str]	  =	32
														lowerCamelCase__ :     Union[str, Any]	  =	16

							lowerCamelCase__ :     List[Any]	  =	ViTMAEForPreTraining(UpperCamelCase				)

							lowerCamelCase__ :     str	  =	torch.hub.load_state_dict_from_url(UpperCamelCase    ,      map_location="""cpu"""				)["""model"""]

							lowerCamelCase__ :     Union[str, Any]	  =	ViTMAEImageProcessor(size=config.image_size				)

							lowerCamelCase__ :     List[str]	  =	convert_state_dict(UpperCamelCase    ,      UpperCamelCase				)

							model.load_state_dict(UpperCamelCase				)
							model.eval()

							lowerCamelCase__ :     Union[str, Any]	  =	"""https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg"""

							lowerCamelCase__ :     List[Any]	  =	Image.open(requests.get(UpperCamelCase    ,      stream=UpperCamelCase				).raw				)
							lowerCamelCase__ :     str	  =	ViTMAEImageProcessor(size=config.image_size				)
							lowerCamelCase__ :     Any	  =	image_processor(images=UpperCamelCase    ,      return_tensors="""pt"""				)

							# forward pass
							torch.manual_seed(2				)
							lowerCamelCase__ :     Optional[Any]	  =	model(**UpperCamelCase				)
							lowerCamelCase__ :     Optional[Any]	  =	outputs.logits

							if "large" in checkpoint_url:
														lowerCamelCase__ :     List[Any]	  =	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:
														lowerCamelCase__ :     Optional[Any]	  =	torch.tensor(
														    [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]]				)
							else:
														lowerCamelCase__ :     int	  =	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     :      str   					=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     :      Tuple   					=parser.parse_args()
			convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)

