





"""simple docstring"""






import argparse
from pathlib import Path

import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version

from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse('''0.12.2'''):
		raise Exception('''requires fairseq >= 0.12.2''')
if version.parse(fairseq.__version__) > version.parse('''2'''):
		raise Exception('''requires fairseq < v2''')

logging.set_verbosity_info()
A	     =					logging.get_logger(__name__)

A	     =					'''Hello, World!'''
A	     =					'''en_XX'''

def       __A (     a_  :str				,    a_  :str				,    a_  :bool)						->						Optional[int]:
				__a	:  List[Any]         =					Path('''data_bin''')
				__a	:  Optional[int]         =					FairseqXmodModel.from_pretrained(
				    model_name_or_path=str(Path(a_).parent)				,    checkpoint_file=Path(a_).name				,    _name='''xmod_base'''				,    arch='''xmod_base'''				,    task='''multilingual_masked_lm'''				,    data_name_or_path=str(a_)				,    bpe='''sentencepiece'''				,    sentencepiece_model=str(Path(a_).parent / '''sentencepiece.bpe.model''')				,    src_dict=str(data_dir / '''dict.txt''')				,    )
				xmod.eval()  # disable dropout
				print(a_)

				__a	:  List[str]         =					xmod.model.encoder.sentence_encoder
				__a	:  List[Any]         =					XmodConfig(
				    vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings				,    hidden_size=xmod.cfg.model.encoder_embed_dim				,    num_hidden_layers=xmod.cfg.model.encoder_layers				,    num_attention_heads=xmod.cfg.model.encoder_attention_heads				,    intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim				,    max_position_embeddings=5_14				,    type_vocab_size=1				,    layer_norm_eps=1e-5				,    pre_norm=xmod.cfg.model.encoder_normalize_before				,    adapter_reduction_factor=getattr(xmod.cfg.model				,    '''bottleneck'''				,    2)				,    adapter_layer_norm=xmod.cfg.model.adapter_layer_norm				,    adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm				,    ln_before_adapter=xmod.cfg.model.ln_before_adapter				,    languages=xmod.cfg.model.languages				,    )
				if classification_head:
								__a	:  Union[str, Any]         =					xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

				print('''Our X-MOD config:'''				,    a_)

				__a	:  List[str]         =					XmodForSequenceClassification(a_) if classification_head else XmodForMaskedLM(a_)
				model.eval()

				# Now let's copy all the weights.
				# Embeddings
				__a	:  Tuple         =					xmod_sent_encoder.embed_tokens.weight
				__a	:  Union[str, Any]         =					xmod_sent_encoder.embed_positions.weight
				__a	:  Union[str, Any]         =					torch.zeros_like(
				    model.roberta.embeddings.token_type_embeddings.weight)  # just zero them out b/c xmod doesn't use them.

				__a	:  Optional[int]         =					xmod_sent_encoder.layernorm_embedding.weight
				__a	:  List[Any]         =					xmod_sent_encoder.layernorm_embedding.bias

				for i in range(config.num_hidden_layers):
								# Encoder: start of layer
								__a	:  Dict         =					model.roberta.encoder.layer[i]
								__a	:  Optional[int]         =					xmod_sent_encoder.layers[i]

								# self attention
								__a	:  str         =					layer.attention.self
								if not (
								    xmod_layer.self_attn.k_proj.weight.data.shape
								    == xmod_layer.self_attn.q_proj.weight.data.shape
								    == xmod_layer.self_attn.v_proj.weight.data.shape
								    == torch.Size((config.hidden_size, config.hidden_size))
								):
												raise AssertionError('''Dimensions of self-attention weights do not match.''')

								__a	:  Union[str, Any]         =					xmod_layer.self_attn.q_proj.weight
								__a	:  Tuple         =					xmod_layer.self_attn.q_proj.bias
								__a	:  Any         =					xmod_layer.self_attn.k_proj.weight
								__a	:  Dict         =					xmod_layer.self_attn.k_proj.bias
								__a	:  List[str]         =					xmod_layer.self_attn.v_proj.weight
								__a	:  Dict         =					xmod_layer.self_attn.v_proj.bias

								# self-attention output
								__a	:  Optional[int]         =					layer.attention.output
								if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
												raise AssertionError('''Dimensions of self-attention output weights do not match.''')
								__a	:  int         =					xmod_layer.self_attn.out_proj.weight
								__a	:  Any         =					xmod_layer.self_attn.out_proj.bias
								__a	:  Any         =					xmod_layer.self_attn_layer_norm.weight
								__a	:  Any         =					xmod_layer.self_attn_layer_norm.bias

								# intermediate
								__a	:  Any         =					layer.intermediate
								if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
												raise AssertionError('''Dimensions of intermediate weights do not match.''')
								__a	:  Dict         =					xmod_layer.fca.weight
								__a	:  int         =					xmod_layer.fca.bias

								# output
								__a	:  Optional[Any]         =					layer.output
								if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
												raise AssertionError('''Dimensions of feed-forward weights do not match.''')
								__a	:  str         =					xmod_layer.fca.weight
								__a	:  int         =					xmod_layer.fca.bias
								__a	:  Any         =					xmod_layer.final_layer_norm.weight
								__a	:  List[str]         =					xmod_layer.final_layer_norm.bias
								if bert_output.adapter_layer_norm is not None:
												__a	:  Tuple         =					xmod_layer.adapter_layer_norm.weight
												__a	:  Dict         =					xmod_layer.adapter_layer_norm.bias

								if sorted(bert_output.adapter_modules.keys()) != sorted(xmod_layer.adapter_modules.keys()):
												raise AssertionError('''Lists of language adapters do not match.''')
								for lang_code, adapter in xmod_layer.adapter_modules.items():
												__a	:  Any         =					bert_output.adapter_modules[lang_code]
												__a	:  List[Any]         =					xmod_layer.adapter_modules[lang_code]
												__a	:  List[str]         =					from_adapter.fca.weight
												__a	:  int         =					from_adapter.fca.bias
												__a	:  Tuple         =					from_adapter.fca.weight
												__a	:  Optional[int]         =					from_adapter.fca.bias

								# end of layer

				if xmod_sent_encoder.layer_norm is not None:
								__a	:  Union[str, Any]         =					xmod_sent_encoder.layer_norm.weight
								__a	:  Union[str, Any]         =					xmod_sent_encoder.layer_norm.bias

				if classification_head:
								__a	:  str         =					xmod.model.classification_heads['''mnli'''].dense.weight
								__a	:  Union[str, Any]         =					xmod.model.classification_heads['''mnli'''].dense.bias
								__a	:  Optional[int]         =					xmod.model.classification_heads['''mnli'''].out_proj.weight
								__a	:  str         =					xmod.model.classification_heads['''mnli'''].out_proj.bias
				else:
								# LM Head
								__a	:  Tuple         =					xmod.model.encoder.lm_head.dense.weight
								__a	:  List[Any]         =					xmod.model.encoder.lm_head.dense.bias
								__a	:  Tuple         =					xmod.model.encoder.lm_head.layer_norm.weight
								__a	:  int         =					xmod.model.encoder.lm_head.layer_norm.bias
								__a	:  int         =					xmod.model.encoder.lm_head.weight
								__a	:  Optional[Any]         =					xmod.model.encoder.lm_head.bias

				# Let's check that we get the same results.
				__a	:  Dict         =					xmod.encode(a_).unsqueeze(0)  # batch of size 1
				model.roberta.set_default_language(a_)

				__a	:  str         =					model(a_)[0]
				if classification_head:
								__a	:  Optional[Any]         =					xmod.model.classification_heads['''mnli'''](xmod.extract_features(a_))
				else:
								__a	:  List[Any]         =					xmod.model(a_				,    lang_id=[SAMPLE_LANGUAGE])[0]
				print(our_output.shape				,    their_output.shape)
				__a	:  str         =					torch.max(torch.abs(our_output - their_output)).item()
				print(F"""max_absolute_diff = {max_absolute_diff}""")  # ~ 1e-7
				__a	:  Optional[int]         =					torch.allclose(a_				,    a_				,    atol=1e-3)
				print('''Do both models output the same tensors?'''				,    '''🔥''' if success else '''💩''')
				if not success:
								raise Exception('''Something went wRoNg''')

				Path(a_).mkdir(parents=a_				,    exist_ok=a_)
				print(F"""Saving model to {pytorch_dump_folder_path}""")
				model.save_pretrained(a_)


if __name__ == "__main__":
		A	     =					argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '''--xmod_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.'''
		)
		parser.add_argument(
		    '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
		)
		parser.add_argument(
		    '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.'''
		)
		A	     =					parser.parse_args()
		convert_xmod_checkpoint_to_pytorch(
		    args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
		)






"""simple docstring"""






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 logging


A	     =					logging.get_logger(__name__)
A	     =					{'''vocab_file''': '''spiece.model'''}

A	     =					{
    '''vocab_file''': {
        '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''',
        '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''',
        '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''',
        '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''',
        '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''',
        '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''',
        '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''',
        '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''',
    }
}

A	     =					{
    '''albert-base-v1''': 512,
    '''albert-large-v1''': 512,
    '''albert-xlarge-v1''': 512,
    '''albert-xxlarge-v1''': 512,
    '''albert-base-v2''': 512,
    '''albert-large-v2''': 512,
    '''albert-xlarge-v2''': 512,
    '''albert-xxlarge-v2''': 512,
}

A	     =					'''▁'''




class 			__lowercase     (     _UpperCamelCase							):







					'''simple docstring'''




					__lowerCAmelCase					=					VOCAB_FILES_NAMES
					__lowerCAmelCase					=					PRETRAINED_VOCAB_FILES_MAP
					__lowerCAmelCase					=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES







					def __init__(  self		,     _UpperCAmelCase		,     _UpperCAmelCase=True		,     _UpperCAmelCase=True		,     _UpperCAmelCase=False		,     _UpperCAmelCase="[CLS]"		,     _UpperCAmelCase="[SEP]"		,     _UpperCAmelCase="<unk>"		,     _UpperCAmelCase="[SEP]"		,     _UpperCAmelCase="<pad>"		,     _UpperCAmelCase="[CLS]"		,     _UpperCAmelCase="[MASK]"		,     _UpperCAmelCase = None		,     **_UpperCAmelCase		,     ):
									# Mask token behave like a normal word, i.e. include the space before it and
									# is included in the raw text, there should be a match in a non-normalized sentence.
									__a	:  int         =					(
									    AddedToken(_UpperCAmelCase		,     lstrip=_UpperCAmelCase		,     rstrip=_UpperCAmelCase		,     normalized=_UpperCAmelCase       )
									    if isinstance(_UpperCAmelCase		,     _UpperCAmelCase       )
									    else mask_token
									)

									__a	:  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		,     sp_model_kwargs=self.sp_model_kwargs		,     **_UpperCAmelCase		,     )

									__a	:  Tuple         =					do_lower_case
									__a	:  Optional[Any]         =					remove_space
									__a	:  Optional[Any]         =					keep_accents
									__a	:  Union[str, Any]         =					vocab_file

									__a	:  List[str]         =					spm.SentencePieceProcessor(**self.sp_model_kwargs       )
									self.sp_model.Load(_UpperCAmelCase       )







					@property
					def 	_lowerCamelCase						(  self       ):
									return len(self.sp_model       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  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       ):
									__a	:  str         =					self.__dict__.copy()
									__a	:  Tuple         =					None
									return state







					def __setstate__(  self		,     _UpperCAmelCase       ):
									__a	:  Any         =					d

									# for backward compatibility
									if not hasattr(self		,     '''sp_model_kwargs'''       ):
													__a	:  Optional[Any]         =					{}

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







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									if self.remove_space:
													__a	:  Any         =					''' '''.join(inputs.strip().split()       )
									else:
													__a	:  Tuple         =					inputs
									__a	:  Union[str, Any]         =					outputs.replace('''``'''		,     '''"'''       ).replace('''\'\''''		,     '''"'''       )

									if not self.keep_accents:
													__a	:  List[str]         =					unicodedata.normalize('''NFKD'''		,     _UpperCAmelCase       )
													__a	:  Optional[int]         =					''''''.join([c for c in outputs if not unicodedata.combining(_UpperCAmelCase       )]       )
									if self.do_lower_case:
													__a	:  Optional[Any]         =					outputs.lower()

									return outputs







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									__a	:  int         =					self.preprocess_text(_UpperCAmelCase       )
									__a	:  Tuple         =					self.sp_model.encode(_UpperCAmelCase		,     out_type=_UpperCAmelCase       )
									__a	:  int         =					[]
									for piece in pieces:
													if len(_UpperCAmelCase       ) > 1 and piece[-1] == str(''','''       ) and piece[-2].isdigit():
																	__a	:  List[str]         =					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:
																									__a	:  Tuple         =					cur_pieces[1:]
																					else:
																									__a	:  Optional[Any]         =					cur_pieces[0][1:]
																	cur_pieces.append(piece[-1]       )
																	new_pieces.extend(_UpperCAmelCase       )
													else:
																	new_pieces.append(_UpperCAmelCase       )

									return new_pieces







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									return self.sp_model.PieceToId(_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									return self.sp_model.IdToPiece(_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									__a	:  List[str]         =					[]
									__a	:  str         =					''''''
									__a	:  Any         =					False
									for token in tokens:
													# make sure that special tokens are not decoded using sentencepiece model
													if token in self.all_special_tokens:
																	if not prev_is_special:
																					out_string += " "
																	out_string += self.sp_model.decode(_UpperCAmelCase       ) + token
																	__a	:  Tuple         =					True
																	__a	:  Tuple         =					[]
													else:
																	current_sub_tokens.append(_UpperCAmelCase       )
																	__a	:  Optional[int]         =					False
									out_string += self.sp_model.decode(_UpperCAmelCase       )
									return out_string.strip()







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase = None       ):
									__a	:  int         =					[self.sep_token_id]
									__a	:  Union[str, Any]         =					[self.cls_token_id]
									if token_ids_a is None:
													return cls + token_ids_a + sep
									return cls + token_ids_a + sep + token_ids_a + sep







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase = None		,     _UpperCAmelCase = 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 [1] + ([0] * len(_UpperCAmelCase       )) + [1] + ([0] * len(_UpperCAmelCase       )) + [1]
									return [1] + ([0] * len(_UpperCAmelCase       )) + [1]







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase = None       ):
									__a	:  Union[str, Any]         =					[self.sep_token_id]
									__a	:  Tuple         =					[self.cls_token_id]

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







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase = None       ):
									if not os.path.isdir(_UpperCAmelCase       ):
													logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""       )
													return
									__a	:  List[str]         =					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:
																	__a	:  Any         =					self.sp_model.serialized_model_proto()
																	fi.write(_UpperCAmelCase       )

									return (out_vocab_file,)