'''simple docstring'''




# Usage:
# ./gen-card-facebook-wmt19.py

import os
from pathlib import Path






def 				snake_case__							(			_A:					Optional[Any]      ,   _A:					str      ,   _A:					Union[str, Any] )    ->	Dict:

		'''simple docstring'''


		lowerCAmelCase   					=  {
		    """en""": """Machine learning is great, isn't it?""",
		    """ru""": """Машинное обучение - это здорово, не так ли?""",
		    """de""": """Maschinelles Lernen ist großartig, oder?""",
		}

		# BLUE scores as follows:
		# "pair": [fairseq, transformers]
		lowerCAmelCase   					=  {
		    """ru-en""": ["""[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)""", """39.20"""],
		    """en-ru""": ["""[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)""", """33.47"""],
		    """en-de""": ["""[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)""", """42.83"""],
		    """de-en""": ["""[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)""", """41.35"""],
		}
		lowerCAmelCase   					=  f"{src_lang}-{tgt_lang}"

		lowerCAmelCase   					=  f"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair   | fairseq | transformers\n-------|---------|----------\n{pair}  | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n  year={{2020}},\n  title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n  author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n  booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n"
		os.makedirs(_A      ,   exist_ok=_A )
		lowerCAmelCase   					=  os.path.join(_A      ,   """README.md""" )
		print(f"Generating {path}" )
		with open(_A      ,   """w"""      ,   encoding="""utf-8""" ) as f:
				f.write(_A )


# make sure we are under the root of the project
__lowercase          =  Path(__file__).resolve().parent.parent.parent
__lowercase          =  repo_dir / '''model_cards'''

for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
						__lowercase    ,     __lowercase    ,     __lowercase          =  model_name.split('''-''')
						__lowercase          =  model_cards_dir / '''facebook''' / model_name
						write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)





'''simple docstring'''




import argparse
import glob
import logging
import os
import time
from argparse import Namespace

import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from torch.utils.data import DataLoader, TensorDataset

from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes, glue_tasks_num_labels
from transformers import glue_processors as processors


__lowercase          =  logging.getLogger(__name__)






class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     Any      =       '''sequence-classification'''



			def __init__(   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					if type(__lowerCAmelCase) == dict:
							lowerCAmelCase   					=  Namespace(**__lowerCAmelCase)
					lowerCAmelCase   					=  glue_output_modes[hparams.task]
					lowerCAmelCase   					=  glue_tasks_num_labels[hparams.task]

					super().__init__(__lowerCAmelCase       ,    __lowerCAmelCase       ,    self.mode)



			def 							a_       (   self       ,    **__lowerCAmelCase):




					"""simple docstring"""


					return self.model(**__lowerCAmelCase)



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}

					if self.config.model_type not in ["distilbert", "bart"]:
							lowerCAmelCase   					=  batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None

					lowerCAmelCase   					=  self(**__lowerCAmelCase)
					lowerCAmelCase   					=  outputs[0]

					lowerCAmelCase   					=  self.trainer.lr_schedulers[0]["""scheduler"""]
					lowerCAmelCase   					=  {"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]}
					return {"loss": loss, "log": tensorboard_logs}



			def 							a_       (   self):




					"""simple docstring"""


					lowerCAmelCase   					=  self.hparams
					lowerCAmelCase   					=  processors[args.task]()
					lowerCAmelCase   					=  processor.get_labels()

					for mode in ["train", "dev"]:
							lowerCAmelCase   					=  self._feature_file(__lowerCAmelCase)
							if os.path.exists(__lowerCAmelCase) and not args.overwrite_cache:
									logger.info("""Loading features from cached file %s"""       ,    __lowerCAmelCase)
							else:
									logger.info("""Creating features from dataset file at %s"""       ,    args.data_dir)
									lowerCAmelCase   					=  (
									    processor.get_dev_examples(args.data_dir)
									    if mode == """dev"""
									    else processor.get_train_examples(args.data_dir)
									)
									lowerCAmelCase   					=  convert_examples_to_features(
									    __lowerCAmelCase       ,    self.tokenizer       ,    max_length=args.max_seq_length       ,    label_list=self.labels       ,    output_mode=args.glue_output_mode       ,    )
									logger.info("""Saving features into cached file %s"""       ,    __lowerCAmelCase)
									torch.save(__lowerCAmelCase       ,    __lowerCAmelCase)



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase = False):




					"""simple docstring"""


					lowerCAmelCase   					=  """dev""" if mode == """test""" else mode

					lowerCAmelCase   					=  self._feature_file(__lowerCAmelCase)
					logger.info("""Loading features from cached file %s"""       ,    __lowerCAmelCase)
					lowerCAmelCase   					=  torch.load(__lowerCAmelCase)
					lowerCAmelCase   					=  torch.tensor([f.input_ids for f in features]       ,    dtype=torch.long)
					lowerCAmelCase   					=  torch.tensor([f.attention_mask for f in features]       ,    dtype=torch.long)
					lowerCAmelCase   					=  torch.tensor([f.token_type_ids for f in features]       ,    dtype=torch.long)
					if self.hparams.glue_output_mode == "classification":
							lowerCAmelCase   					=  torch.tensor([f.label for f in features]       ,    dtype=torch.long)
					elif self.hparams.glue_output_mode == "regression":
							lowerCAmelCase   					=  torch.tensor([f.label for f in features]       ,    dtype=torch.float)

					return DataLoader(
					    TensorDataset(__lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase)       ,    batch_size=__lowerCAmelCase       ,    shuffle=__lowerCAmelCase       ,    )



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}

					if self.config.model_type not in ["distilbert", "bart"]:
							lowerCAmelCase   					=  batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None

					lowerCAmelCase   					=  self(**__lowerCAmelCase)
					lowerCAmelCase					,     lowerCAmelCase   					=  outputs[:2]
					lowerCAmelCase   					=  logits.detach().cpu().numpy()
					lowerCAmelCase   					=  inputs["""labels"""].detach().cpu().numpy()

					return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}



			def 							a_       (   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  torch.stack([x["""val_loss"""] for x in outputs]).mean().detach().cpu().item()
					lowerCAmelCase   					=  np.concatenate([x["""pred"""] for x in outputs]       ,    axis=0)

					if self.hparams.glue_output_mode == "classification":
							lowerCAmelCase   					=  np.argmax(__lowerCAmelCase       ,    axis=1)
					elif self.hparams.glue_output_mode == "regression":
							lowerCAmelCase   					=  np.squeeze(__lowerCAmelCase)

					lowerCAmelCase   					=  np.concatenate([x["""target"""] for x in outputs]       ,    axis=0)
					lowerCAmelCase   					=  [[] for _ in range(out_label_ids.shape[0])]
					lowerCAmelCase   					=  [[] for _ in range(out_label_ids.shape[0])]

					lowerCAmelCase   					=  {**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task       ,    __lowerCAmelCase       ,    __lowerCAmelCase)}

					lowerCAmelCase   					=  dict(results.items())
					lowerCAmelCase   					=  results
					return ret, preds_list, out_label_list



			def 							a_       (   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase					,     lowerCAmelCase					,     lowerCAmelCase   					=  self._eval_end(__lowerCAmelCase)
					lowerCAmelCase   					=  ret["""log"""]
					return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}



			def 							a_       (   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase					,     lowerCAmelCase					,     lowerCAmelCase   					=  self._eval_end(__lowerCAmelCase)
					lowerCAmelCase   					=  ret["""log"""]
					# `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
					return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}







			@staticmethod
			def 							a_       (   __lowerCAmelCase       ,    __lowerCAmelCase):




					"""simple docstring"""


					BaseTransformer.add_model_specific_args(__lowerCAmelCase       ,    __lowerCAmelCase)
					parser.add_argument(
					    """--max_seq_length"""       ,    default=128       ,    type=__lowerCAmelCase       ,    help=(
					        """The maximum total input sequence length after tokenization. Sequences longer """
					        """than this will be truncated, sequences shorter will be padded."""
					    )       ,    )

					parser.add_argument(
					    """--task"""       ,    default=""""""       ,    type=__lowerCAmelCase       ,    required=__lowerCAmelCase       ,    help="""The GLUE task to run"""       ,    )
					parser.add_argument(
					    """--gpus"""       ,    default=0       ,    type=__lowerCAmelCase       ,    help="""The number of GPUs allocated for this, it is by default 0 meaning none"""       ,    )

					parser.add_argument(
					    """--overwrite_cache"""       ,    action="""store_true"""       ,    help="""Overwrite the cached training and evaluation sets""")

					return parser







def 				snake_case__							(			)    ->	Optional[Any]:

		'''simple docstring'''


		lowerCAmelCase   					=  argparse.ArgumentParser()
		add_generic_args(_A      ,   os.getcwd() )
		lowerCAmelCase   					=  GLUETransformer.add_model_specific_args(_A      ,   os.getcwd() )
		lowerCAmelCase   					=  parser.parse_args()

		# If output_dir not provided, a folder will be generated in pwd
		if args.output_dir is None:
				lowerCAmelCase   					=  os.path.join(
				    """./results"""      ,   f"{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}"      ,   )
				os.makedirs(args.output_dir )

		lowerCAmelCase   					=  GLUETransformer(_A )
		lowerCAmelCase   					=  generic_train(_A      ,   _A )

		# Optionally, predict on dev set and write to output_dir
		if args.do_predict:
				lowerCAmelCase   					=  sorted(glob.glob(os.path.join(args.output_dir      ,   """checkpoint-epoch=*.ckpt""" )      ,   recursive=_A ) )
				lowerCAmelCase   					=  model.load_from_checkpoint(checkpoints[-1] )
				return trainer.test(_A )


if __name__ == "__main__":
						main()




