






'''simple docstring'''



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

import os
from pathlib import Path







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__	, UpperCamelCase__   ):
			UpperCAmelCase__					:   List[Any]       				=       {
			    '''en''': '''Machine learning is great, isn\'t it?''',
			    '''ru''': '''Машинное обучение - это здорово, не так ли?''',
			    '''de''': '''Maschinelles Lernen ist großartig, oder?''',
			}

			# BLUE scores as follows:
			# "pair": [fairseq, transformers]
			UpperCAmelCase__					:   int       				=       {
			    '''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'''],
			}
			UpperCAmelCase__					:   List[Any]       				=       f'''{src_lang}-{tgt_lang}'''

			UpperCAmelCase__					:   Any       				=       f'''
---
language: 
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt19
- facebook
license: apache-2.0
datasets:
- wmt19
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.

For more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).

The abbreviation FSMT stands for FairSeqMachineTranslation

All four models are available:

* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)
* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)
* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)
* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)

## Intended uses & limitations

#### How to use

```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"
tokenizer = FSMTTokenizer.from_pretrained(mname)
model = FSMTForConditionalGeneration.from_pretrained(mname)

input = \"{texts[src_lang]}\"
input_ids = tokenizer.encode(input, return_tensors=\"pt\")
outputs = model.generate(input_ids)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(decoded) # {texts[tgt_lang]}

```

#### Limitations and bias

- 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)

## Training data

Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).

## Eval results

pair   | fairseq | transformers
-------|---------|----------
{pair}  | {scores[pair][0]} | {scores[pair][1]}

The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:
- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).
- re-ranking

The score was calculated using this code:

```bash
git clone https://github.com/huggingface/transformers
cd transformers
export PAIR={pair}
export DATA_DIR=data/$PAIR
export SAVE_DIR=data/$PAIR
export BS=8
export NUM_BEAMS=15
mkdir -p $DATA_DIR
sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
echo $PAIR
PYTHONPATH=\"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
```
note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.

## Data Sources

- [training, etc.](http://www.statmt.org/wmt19/)
- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)


### BibTeX entry and citation info

```bibtex
@inproceedings{{...,
  year={{2020}},
  title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},
  author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},
  booktitle={{Proc. of WMT}},
}}
```


## TODO

- port model ensemble (fairseq uses 4 model checkpoints)

'''
			os.makedirs(UpperCamelCase__	, exist_ok=UpperCamelCase__   )
			UpperCAmelCase__					:   Union[str, Any]       				=       os.path.join(UpperCamelCase__	, """README.md"""   )
			print(f'''Generating {path}'''   )
			with open(UpperCamelCase__	, """w"""	, encoding="""utf-8"""   ) as f:
						f.write(UpperCamelCase__   )


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

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



'''simple docstring'''



import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


__A		=logging.get_logger(__name__)

__A		='▁'

__A		={'vocab_file': 'sentencepiece.bpe.model'}

__A		={
    'vocab_file': {
        'facebook/mbart-large-50-one-to-many-mmt': (
            'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model'
        ),
    }
}

__A		={
    'facebook/mbart-large-50-one-to-many-mmt': 10_24,
}

# fmt: off
__A		=['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN', 'af_ZA', 'az_AZ', 'bn_IN', 'fa_IR', 'he_IL', 'hr_HR', 'id_ID', 'ka_GE', 'km_KH', 'mk_MK', 'ml_IN', 'mn_MN', 'mr_IN', 'pl_PL', 'ps_AF', 'pt_XX', 'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH', 'tl_XX', 'uk_UA', 'ur_PK', 'xh_ZA', 'gl_ES', 'sl_SI']


class 						_snake_case   (       a__		):
					lowerCAmelCase :int						=   VOCAB_FILES_NAMES
					lowerCAmelCase :Dict						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowerCAmelCase :str						=   PRETRAINED_VOCAB_FILES_MAP
					lowerCAmelCase :List[str]						=   ['''input_ids''', '''attention_mask''']

					lowerCAmelCase :List[int]						=   []
					lowerCAmelCase :List[int]						=   []




					def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase=None							,							_lowerCamelCase=None							,							_lowerCamelCase="</s>"							,							_lowerCamelCase="</s>"							,							_lowerCamelCase="<s>"							,							_lowerCamelCase="<unk>"							,							_lowerCamelCase="<pad>"							,							_lowerCamelCase="<mask>"							,							_lowerCamelCase = None							,							**_lowerCamelCase							,							):
								# Mask token behave like a normal word, i.e. include the space before it
								UpperCAmelCase__					:   List[str]       				=       AddedToken(_lowerCamelCase							,							lstrip=_lowerCamelCase							,							rstrip=_lowerCamelCase) if isinstance(_lowerCamelCase							,							_lowerCamelCase) else mask_token

								UpperCAmelCase__					:   Dict       				=       {} if sp_model_kwargs is None else sp_model_kwargs

								UpperCAmelCase__					:   Dict       				=       kwargs.get("""additional_special_tokens"""							,							[])
								kwargs["additional_special_tokens"] += [
								    code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
								]

								super().__init__(
								    src_lang=_lowerCamelCase							,							tgt_lang=_lowerCamelCase							,							eos_token=_lowerCamelCase							,							unk_token=_lowerCamelCase							,							sep_token=_lowerCamelCase							,							cls_token=_lowerCamelCase							,							pad_token=_lowerCamelCase							,							mask_token=_lowerCamelCase							,							sp_model_kwargs=self.sp_model_kwargs							,							**_lowerCamelCase							,							)

								UpperCAmelCase__					:   str       				=       spm.SentencePieceProcessor(**self.sp_model_kwargs)
								self.sp_model.Load(str(_lowerCamelCase))
								UpperCAmelCase__					:   int       				=       vocab_file

								# Original fairseq vocab and spm vocab must be "aligned":
								# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
								# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
								# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
								# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

								# Mimic fairseq token-to-id alignment for the first 4 token
								UpperCAmelCase__					:   Union[str, Any]       				=       {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

								# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
								UpperCAmelCase__					:   List[str]       				=       1

								UpperCAmelCase__					:   Optional[int]       				=       len(self.sp_model)
								UpperCAmelCase__					:   List[str]       				=       {
								    code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_lowerCamelCase)
								}
								UpperCAmelCase__					:   Optional[int]       				=       {v: k for k, v in self.lang_code_to_id.items()}
								UpperCAmelCase__					:   Optional[int]       				=       len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset

								self.fairseq_tokens_to_ids.update(self.lang_code_to_id)
								UpperCAmelCase__					:   Union[str, Any]       				=       {v: k for k, v in self.fairseq_tokens_to_ids.items()}

								UpperCAmelCase__					:   Dict       				=       src_lang if src_lang is not None else """en_XX"""
								UpperCAmelCase__					:   str       				=       self.lang_code_to_id[self._src_lang]
								UpperCAmelCase__					:   Tuple       				=       tgt_lang
								self.set_src_lang_special_tokens(self._src_lang)




					@property
					def 			snake_case__  ( self):
								return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1  # Plus 1 for the mask token




					@property
					def 			snake_case__  ( self):
								return self._src_lang




					@src_lang.setter
					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   str       				=       new_src_lang
								self.set_src_lang_special_tokens(self._src_lang)




					def __getstate__( self):
								UpperCAmelCase__					:   int       				=       self.__dict__.copy()
								UpperCAmelCase__					:   Tuple       				=       None
								return state




					def __setstate__( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Union[str, Any]       				=       d

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

								UpperCAmelCase__					:   Any       				=       spm.SentencePieceProcessor(**self.sp_model_kwargs)
								self.sp_model.Load(self.vocab_file)




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   Dict       				=       {self.convert_ids_to_tokens(_lowerCamelCase): i for i in range(self.vocab_size)}
								vocab.update(self.added_tokens_encoder)
								return vocab




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self.sp_model.encode(_lowerCamelCase							,							out_type=_lowerCamelCase)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								if token in self.fairseq_tokens_to_ids:
											return self.fairseq_tokens_to_ids[token]
								UpperCAmelCase__					:   Dict       				=       self.sp_model.PieceToId(_lowerCamelCase)

								# Need to return unknown token if the SP model returned 0
								return spm_id + self.fairseq_offset if spm_id else self.unk_token_id




					def 			snake_case__  ( self							,							_lowerCamelCase):
								if index in self.fairseq_ids_to_tokens:
											return self.fairseq_ids_to_tokens[index]
								return self.sp_model.IdToPiece(index - self.fairseq_offset)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Optional[Any]       				=       []
								UpperCAmelCase__					:   List[Any]       				=       """"""
								UpperCAmelCase__					:   Optional[int]       				=       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(_lowerCamelCase) + token
														UpperCAmelCase__					:   Tuple       				=       True
														UpperCAmelCase__					:   List[str]       				=       []
											else:
														current_sub_tokens.append(_lowerCamelCase)
														UpperCAmelCase__					:   Dict       				=       False
								out_string += self.sp_model.decode(_lowerCamelCase)
								return out_string.strip()




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								if not os.path.isdir(_lowerCamelCase):
											logger.error(f'''Vocabulary path ({save_directory}) should be a directory''')
											return
								UpperCAmelCase__					:   Any       				=       os.path.join(
								    _lowerCamelCase							,							(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""])

								if os.path.abspath(self.vocab_file) != os.path.abspath(_lowerCamelCase) and os.path.isfile(self.vocab_file):
											copyfile(self.vocab_file							,							_lowerCamelCase)
								elif not os.path.isfile(self.vocab_file):
											with open(_lowerCamelCase							,							"""wb""") as fi:
														UpperCAmelCase__					:   List[str]       				=       self.sp_model.serialized_model_proto()
														fi.write(_lowerCamelCase)

								return (out_vocab_file,)




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None							,							_lowerCamelCase = False):

								if already_has_special_tokens:
											return super().get_special_tokens_mask(
											    token_ids_a=_lowerCamelCase							,							token_ids_a=_lowerCamelCase							,							already_has_special_tokens=_lowerCamelCase)

								UpperCAmelCase__					:   Tuple       				=       [1] * len(self.prefix_tokens)
								UpperCAmelCase__					:   Dict       				=       [1] * len(self.suffix_tokens)
								if token_ids_a is None:
											return prefix_ones + ([0] * len(_lowerCamelCase)) + suffix_ones
								return prefix_ones + ([0] * len(_lowerCamelCase)) + ([0] * len(_lowerCamelCase)) + suffix_ones




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								if token_ids_a is None:
											return self.prefix_tokens + token_ids_a + self.suffix_tokens
								# We don't expect to process pairs, but leave the pair logic for API consistency
								return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							**_lowerCamelCase):
								if src_lang is None or tgt_lang is None:
											raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""")
								UpperCAmelCase__					:   Any       				=       src_lang
								UpperCAmelCase__					:   Dict       				=       self(_lowerCamelCase							,							add_special_tokens=_lowerCamelCase							,							return_tensors=_lowerCamelCase							,							**_lowerCamelCase)
								UpperCAmelCase__					:   List[Any]       				=       self.convert_tokens_to_ids(_lowerCamelCase)
								UpperCAmelCase__					:   List[str]       				=       tgt_lang_id
								return inputs




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = "en_XX"							,							_lowerCamelCase = None							,							_lowerCamelCase = "ro_RO"							,							**_lowerCamelCase							,							):
								UpperCAmelCase__					:   Tuple       				=       src_lang
								UpperCAmelCase__					:   Optional[Any]       				=       tgt_lang
								return super().prepare_seqaseq_batch(_lowerCamelCase							,							_lowerCamelCase							,							**_lowerCamelCase)




					def 			snake_case__  ( self):
								return self.set_src_lang_special_tokens(self.src_lang)




					def 			snake_case__  ( self):
								return self.set_tgt_lang_special_tokens(self.tgt_lang)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Tuple       				=       self.lang_code_to_id[src_lang]
								UpperCAmelCase__					:   Optional[int]       				=       [self.cur_lang_code_id]
								UpperCAmelCase__					:   Optional[int]       				=       [self.eos_token_id]




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   List[Any]       				=       self.lang_code_to_id[tgt_lang]
								UpperCAmelCase__					:   Dict       				=       [self.cur_lang_code_id]
								UpperCAmelCase__					:   Optional[int]       				=       [self.eos_token_id]