




"""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 string
import sys


A	     =					1 << 8

A	     =					{
    '''tab''': ord('''\t'''),
    '''newline''': ord('''\r'''),
    '''esc''': 27,
    '''up''': 65 + ARROW_KEY_FLAG,
    '''down''': 66 + ARROW_KEY_FLAG,
    '''right''': 67 + ARROW_KEY_FLAG,
    '''left''': 68 + ARROW_KEY_FLAG,
    '''mod_int''': 91,
    '''undefined''': sys.maxsize,
    '''interrupt''': 3,
    '''insert''': 50,
    '''delete''': 51,
    '''pg_up''': 53,
    '''pg_down''': 54,
}

A	     =					KEYMAP['''up''']
A	     =					KEYMAP['''left''']

if sys.platform == "win32":
		A	     =					[]
		A	     =					{
		    B'''\xe0H''': KEYMAP['''up'''] - ARROW_KEY_FLAG,
		    B'''\x00H''': KEYMAP['''up'''] - ARROW_KEY_FLAG,
		    B'''\xe0P''': KEYMAP['''down'''] - ARROW_KEY_FLAG,
		    B'''\x00P''': KEYMAP['''down'''] - ARROW_KEY_FLAG,
		    B'''\xe0M''': KEYMAP['''right'''] - ARROW_KEY_FLAG,
		    B'''\x00M''': KEYMAP['''right'''] - ARROW_KEY_FLAG,
		    B'''\xe0K''': KEYMAP['''left'''] - ARROW_KEY_FLAG,
		    B'''\x00K''': KEYMAP['''left'''] - ARROW_KEY_FLAG,
		}

for i in range(10):
		A	     =					ord(str(i))

def       __A (     )						->						Dict:
				if os.name == "nt":
								import msvcrt

								__a	:  Optional[Any]         =					'''mbcs'''
								# Flush the keyboard buffer
								while msvcrt.kbhit():
												msvcrt.getch()
								if len(a_) == 0:
												# Read the keystroke
												__a	:  Optional[Any]         =					msvcrt.getch()

												# If it is a prefix char, get second part
												if ch in (b"\x00", b"\xe0"):
																__a	:  Optional[Any]         =					ch + msvcrt.getch()
																# Translate actual Win chars to bullet char types
																try:
																				__a	:  Union[str, Any]         =					chr(WIN_KEYMAP[cha])
																				WIN_CH_BUFFER.append(chr(KEYMAP['''mod_int''']))
																				WIN_CH_BUFFER.append(a_)
																				if ord(a_) in (
																				    KEYMAP["insert"] - 1 << 9,
																				    KEYMAP["delete"] - 1 << 9,
																				    KEYMAP["pg_up"] - 1 << 9,
																				    KEYMAP["pg_down"] - 1 << 9,
																				):
																								WIN_CH_BUFFER.append(chr(1_26))
																				__a	:  str         =					chr(KEYMAP['''esc'''])
																except KeyError:
																				__a	:  str         =					cha[1]
												else:
																__a	:  Optional[Any]         =					ch.decode(a_)
								else:
												__a	:  Union[str, Any]         =					WIN_CH_BUFFER.pop(0)
				elif os.name == "posix":
								import termios
								import tty

								__a	:  Any         =					sys.stdin.fileno()
								__a	:  List[str]         =					termios.tcgetattr(a_)
								try:
												tty.setraw(a_)
												__a	:  int         =					sys.stdin.read(1)
								finally:
												termios.tcsetattr(a_				,    termios.TCSADRAIN				,    a_)
				return ch






def       __A (     )						->						str:
				__a	:  Any         =					get_raw_chars()
				if ord(a_) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
								return char

				elif ord(a_) == KEYMAP["esc"]:
								__a	:  str         =					get_raw_chars()
								if ord(a_) == KEYMAP["mod_int"]:
												__a	:  List[str]         =					get_raw_chars()
												if ord(a_) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(a_) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
																return chr(ord(a_) + ARROW_KEY_FLAG)
												else:
																return KEYMAP["undefined"]
								else:
												return get_raw_chars()

				else:
								if char in string.printable:
												return char
								else:
												return KEYMAP["undefined"]