





"""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()
_UpperCamelCase							=      logging.get_logger(__name__)

_UpperCamelCase							=      'Hello, World!'
_UpperCamelCase							=      'en_XX'






def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							str    ,						SCREAMING_SNAKE_CASE       :							str    ,						SCREAMING_SNAKE_CASE       :							bool   ):


							'''simple docstring'''







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

							__lowerCamelCase      :      Union[str, Any]         =xmod.model.encoder.sentence_encoder
							__lowerCamelCase      :      List[str]         =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      :      str         =xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

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

							__lowerCamelCase      :      Optional[Any]         =XmodForSequenceClassification(SCREAMING_SNAKE_CASE   ) if classification_head else XmodForMaskedLM(SCREAMING_SNAKE_CASE   )
							model.eval()

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

							__lowerCamelCase      :      Optional[Any]         =xmod_sent_encoder.layernorm_embedding.weight
							__lowerCamelCase      :      Any         =xmod_sent_encoder.layernorm_embedding.bias

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

														# self attention
														__lowerCamelCase      :      int         =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      :      Optional[Any]         =xmod_layer.self_attn.q_proj.weight
														__lowerCamelCase      :      List[Any]         =xmod_layer.self_attn.q_proj.bias
														__lowerCamelCase      :      str         =xmod_layer.self_attn.k_proj.weight
														__lowerCamelCase      :      List[Any]         =xmod_layer.self_attn.k_proj.bias
														__lowerCamelCase      :      Optional[int]         =xmod_layer.self_attn.v_proj.weight
														__lowerCamelCase      :      List[Any]         =xmod_layer.self_attn.v_proj.bias

														# self-attention output
														__lowerCamelCase      :      Optional[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[str]         =xmod_layer.self_attn.out_proj.weight
														__lowerCamelCase      :      Optional[int]         =xmod_layer.self_attn.out_proj.bias
														__lowerCamelCase      :      int         =xmod_layer.self_attn_layer_norm.weight
														__lowerCamelCase      :      Union[str, Any]         =xmod_layer.self_attn_layer_norm.bias

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

														# end of layer

							if xmod_sent_encoder.layer_norm is not None:
														__lowerCamelCase      :      Optional[int]         =xmod_sent_encoder.layer_norm.weight
														__lowerCamelCase      :      Optional[Any]         =xmod_sent_encoder.layer_norm.bias

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

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

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

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


if __name__ == "__main__":
							_UpperCamelCase							=      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.'
							)
							_UpperCamelCase							=      parser.parse_args()
							convert_xmod_checkpoint_to_pytorch(
							    args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
							)











"""simple docstring"""





from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


_UpperCamelCase							=      '\\n@misc{wu2016googles,\n      title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n'

_UpperCamelCase							=      '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n'

_UpperCamelCase							=      '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    \'google_bleu\': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results["google_bleu"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results["google_bleu"], 2))\n        0.4\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,  _KWARGS_DESCRIPTION   )
class 		SCREAMING_SNAKE_CASE_							(    datasets.Metric   ):
				"""simple docstring"""




				def 					__lowercase  (     self  :Optional[Any]			):
											return datasets.MetricInfo(
											    description=_DESCRIPTION						,    citation=_CITATION						,    inputs_description=_KWARGS_DESCRIPTION						,    features=datasets.Features(
											        {
											            '''predictions''': datasets.Sequence(datasets.Value('''string'''						,    id='''token'''			)						,    id='''sequence'''			),
											            '''references''': datasets.Sequence(
											                datasets.Sequence(datasets.Value('''string'''						,    id='''token'''			)						,    id='''sequence'''			)						,    id='''references'''			),
											        }			)						,    )




				def 					__lowercase  (     self  :Optional[Any]						,    __lowercase  :List[List[List[str]]]						,    __lowercase  :List[List[str]]						,    __lowercase  :int = 1						,    __lowercase  :int = 4						,    ):
											return {
											    "google_bleu": gleu_score.corpus_gleu(
											        list_of_references=__lowercase						,    hypotheses=__lowercase						,    min_len=__lowercase						,    max_len=__lowercase			)
											}




