
'''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()
__lowercase							:   Any					=     logging.get_logger(__name__)

__lowercase							:   str					=     '''Hello, World!'''
__lowercase							:   Optional[int]					=     '''en_XX'''




def lowercase_	(   _lowercase			,       _lowercase			,       _lowercase				)     ->							str:
					'''simple docstring'''

					lowerCamelCase_					:      int     =		Path('''data_bin'''				)
					lowerCamelCase_					:      List[str]     =		FairseqXmodModel.from_pretrained(
					    model_name_or_path=str(Path(_lowercase				).parent				)			,       checkpoint_file=Path(_lowercase				).name			,       _name='''xmod_base'''			,       arch='''xmod_base'''			,       task='''multilingual_masked_lm'''			,       data_name_or_path=str(_lowercase				)			,       bpe='''sentencepiece'''			,       sentencepiece_model=str(Path(_lowercase				).parent / '''sentencepiece.bpe.model'''				)			,       src_dict=str(data_dir / '''dict.txt'''				)			,       )
					xmod.eval()  # disable dropout
					print(_lowercase				)

					lowerCamelCase_					:      Dict     =		xmod.model.encoder.sentence_encoder
					lowerCamelCase_					:      Optional[int]     =		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=514			,       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:
										lowerCamelCase_					:      int     =		xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

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

					lowerCamelCase_					:      str     =		XmodForSequenceClassification(_lowercase				) if classification_head else XmodForMaskedLM(_lowercase				)
					model.eval()

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

					lowerCamelCase_					:      int     =		xmod_sent_encoder.layernorm_embedding.weight
					lowerCamelCase_					:      Tuple     =		xmod_sent_encoder.layernorm_embedding.bias

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

										# self attention
										lowerCamelCase_					:      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.'''				)

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

										# self-attention output
										lowerCamelCase_					:      Union[str, Any]     =		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.'''				)
										lowerCamelCase_					:      List[Any]     =		xmod_layer.self_attn.out_proj.weight
										lowerCamelCase_					:      Union[str, Any]     =		xmod_layer.self_attn.out_proj.bias
										lowerCamelCase_					:      Any     =		xmod_layer.self_attn_layer_norm.weight
										lowerCamelCase_					:      Dict     =		xmod_layer.self_attn_layer_norm.bias

										# intermediate
										lowerCamelCase_					:      List[str]     =		layer.intermediate
										if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
															raise AssertionError('''Dimensions of intermediate weights do not match.'''				)
										lowerCamelCase_					:      Union[str, Any]     =		xmod_layer.fca.weight
										lowerCamelCase_					:      List[Any]     =		xmod_layer.fca.bias

										# output
										lowerCamelCase_					:      Optional[int]     =		layer.output
										if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
															raise AssertionError('''Dimensions of feed-forward weights do not match.'''				)
										lowerCamelCase_					:      Optional[int]     =		xmod_layer.fca.weight
										lowerCamelCase_					:      List[Any]     =		xmod_layer.fca.bias
										lowerCamelCase_					:      Tuple     =		xmod_layer.final_layer_norm.weight
										lowerCamelCase_					:      str     =		xmod_layer.final_layer_norm.bias
										if bert_output.adapter_layer_norm is not None:
															lowerCamelCase_					:      Dict     =		xmod_layer.adapter_layer_norm.weight
															lowerCamelCase_					:      int     =		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():
															lowerCamelCase_					:      Optional[Any]     =		bert_output.adapter_modules[lang_code]
															lowerCamelCase_					:      Optional[int]     =		xmod_layer.adapter_modules[lang_code]
															lowerCamelCase_					:      Tuple     =		from_adapter.fca.weight
															lowerCamelCase_					:      Optional[Any]     =		from_adapter.fca.bias
															lowerCamelCase_					:      List[Any]     =		from_adapter.fca.weight
															lowerCamelCase_					:      List[str]     =		from_adapter.fca.bias

										# end of layer

					if xmod_sent_encoder.layer_norm is not None:
										lowerCamelCase_					:      Any     =		xmod_sent_encoder.layer_norm.weight
										lowerCamelCase_					:      List[str]     =		xmod_sent_encoder.layer_norm.bias

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

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

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

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


if __name__ == "__main__":
					__lowercase							:   Optional[Any]					=     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.'''
					)
					__lowercase							:   Dict					=     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 shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer

class 	__lowercase				(  _lowercase    ):

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      Any     =		tempfile.mkdtemp()
								lowerCamelCase_					:      Optional[int]     =		5

								# Realm tok
								lowerCamelCase_					:      Any     =		[
								    '''[UNK]''',
								    '''[CLS]''',
								    '''[SEP]''',
								    '''[PAD]''',
								    '''[MASK]''',
								    '''test''',
								    '''question''',
								    '''this''',
								    '''is''',
								    '''the''',
								    '''first''',
								    '''second''',
								    '''third''',
								    '''fourth''',
								    '''fifth''',
								    '''record''',
								    '''want''',
								    '''##want''',
								    '''##ed''',
								    '''wa''',
								    '''un''',
								    '''runn''',
								    '''##ing''',
								    ''',''',
								    '''low''',
								    '''lowest''',
								]
								lowerCamelCase_					:      Optional[int]     =		os.path.join(self.tmpdirname			,   '''realm_tokenizer'''      )
								os.makedirs(A			,   exist_ok=A      )
								lowerCamelCase_					:      str     =		os.path.join(A			,   VOCAB_FILES_NAMES['''vocab_file''']      )
								with open(self.vocab_file			,   '''w'''			,   encoding='''utf-8'''      ) as vocab_writer:
													vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]      )      )

								lowerCamelCase_					:      List[Any]     =		os.path.join(self.tmpdirname			,   '''realm_block_records'''      )
								os.makedirs(A			,   exist_ok=A      )

			def        UpperCAmelCase__ (self      ):
								return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname			,   '''realm_tokenizer'''      )      )

			def        UpperCAmelCase__ (self      ):
								shutil.rmtree(self.tmpdirname      )

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      int     =		RealmConfig(num_block_records=self.num_block_records      )
								return config

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      Optional[int]     =		Dataset.from_dict(
								    {
								        '''id''': ['''0''', '''1'''],
								        '''question''': ['''foo''', '''bar'''],
								        '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']],
								    }      )
								return dataset

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      Any     =		np.array(
								    [
								        B'''This is the first record''',
								        B'''This is the second record''',
								        B'''This is the third record''',
								        B'''This is the fourth record''',
								        B'''This is the fifth record''',
								        B'''This is a longer longer longer record''',
								    ]			,   dtype=A			,   )
								return block_records

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      Dict     =		RealmRetriever(
								    block_records=self.get_dummy_block_records()			,   tokenizer=self.get_tokenizer()			,   )
								return retriever

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      Optional[Any]     =		self.get_config()
								lowerCamelCase_					:      List[Any]     =		self.get_dummy_retriever()
								lowerCamelCase_					:      Dict     =		retriever.tokenizer

								lowerCamelCase_					:      List[Any]     =		np.array([0, 3]			,   dtype='''long'''      )
								lowerCamelCase_					:      int     =		tokenizer(['''Test question''']      ).input_ids
								lowerCamelCase_					:      Any     =		tokenizer(
								    ['''the fourth''']			,   add_special_tokens=A			,   return_token_type_ids=A			,   return_attention_mask=A			,   ).input_ids
								lowerCamelCase_					:      Any     =		config.reader_seq_len

								lowerCamelCase_,      lowerCamelCase_,      lowerCamelCase_,      lowerCamelCase_					:      Tuple     =		retriever(
								    A			,   A			,   answer_ids=A			,   max_length=A			,   return_tensors='''np'''      )

								self.assertEqual(len(A      )			,   2      )
								self.assertEqual(len(A      )			,   2      )
								self.assertEqual(len(A      )			,   2      )
								self.assertEqual(concat_inputs.input_ids.shape			,   (2, 1_0)      )
								self.assertEqual(concat_inputs.attention_mask.shape			,   (2, 1_0)      )
								self.assertEqual(concat_inputs.token_type_ids.shape			,   (2, 1_0)      )
								self.assertEqual(concat_inputs.special_tokens_mask.shape			,   (2, 1_0)      )
								self.assertEqual(
								    tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]      )			,   ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]''']			,   )
								self.assertEqual(
								    tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]      )			,   ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]''']			,   )

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      str     =		self.get_config()
								lowerCamelCase_					:      Optional[Any]     =		self.get_dummy_retriever()
								lowerCamelCase_					:      Optional[int]     =		retriever.tokenizer

								lowerCamelCase_					:      int     =		np.array([0, 3, 5]			,   dtype='''long'''      )
								lowerCamelCase_					:      List[Any]     =		tokenizer(['''Test question''']      ).input_ids
								lowerCamelCase_					:      int     =		tokenizer(
								    ['''the fourth''', '''longer longer''']			,   add_special_tokens=A			,   return_token_type_ids=A			,   return_attention_mask=A			,   ).input_ids
								lowerCamelCase_					:      Tuple     =		config.reader_seq_len

								lowerCamelCase_,      lowerCamelCase_,      lowerCamelCase_,      lowerCamelCase_					:      int     =		retriever(
								    A			,   A			,   answer_ids=A			,   max_length=A			,   return_tensors='''np'''      )

								self.assertEqual([False, True, True]			,   A      )
								self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]			,   A      )
								self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]			,   A      )






			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      Any     =		self.get_dummy_retriever()
								retriever.save_pretrained(os.path.join(self.tmpdirname			,   '''realm_block_records'''      )      )

								# Test local path
								lowerCamelCase_					:      str     =		retriever.from_pretrained(os.path.join(self.tmpdirname			,   '''realm_block_records'''      )      )
								self.assertEqual(retriever.block_records[0]			,   B'''This is the first record'''      )

								# Test mocked remote path
								with patch('''transformers.models.realm.retrieval_realm.hf_hub_download'''      ) as mock_hf_hub_download:
													lowerCamelCase_					:      Dict     =		os.path.join(
													    os.path.join(self.tmpdirname			,   '''realm_block_records'''      )			,   _REALM_BLOCK_RECORDS_FILENAME      )
													lowerCamelCase_					:      str     =		RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa'''      )

								self.assertEqual(retriever.block_records[0]			,   B'''This is the first record'''      )


