





'''simple docstring'''






import os
from pathlib import Path
def 							_lowerCamelCase(  UpperCamelCase__    : Optional[int]    ,       UpperCamelCase__    : Optional[Any]    ,       UpperCamelCase__    : Optional[Any]		)		->  Optional[int]:
				A       :       int							=						{
				    '''en''': '''Machine learning is great, isn\'t it?''',
				    '''ru''': '''Машинное обучение - это здорово, не так ли?''',
				    '''de''': '''Maschinelles Lernen ist großartig, oder?''',
				}

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

				A       :       str							=						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(a__    ,       exist_ok=a__		)
				A       :       List[Any]							=						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
snake_case_     =	Path(__file__).resolve().parent.parent.parent
snake_case_     =	repo_dir / """model_cards"""

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







'''simple docstring'''






import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
     import os

     import jax.numpy as jnp
     from jax import jit

     from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
     from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

     snake_case_     =	"""0.12"""  # assumed parallelism: 8


if is_torch_available():
     import torch
def 							_lowerCamelCase(  UpperCamelCase__    : int    ,       UpperCamelCase__    : Optional[int]    ,       UpperCamelCase__    : Any=None		)		->  List[Any]:
    if rng is None:
        A       :       int							=						random.Random()

    A       :       int							=						1
    for dim in shape:
        total_dims *= dim

    A       :       Union[str, Any]							=						[]
    for _ in range(UpperCamelCase__		):
        values.append(rng.randint(0    ,       vocab_size - 1		)		)

    A       :       Union[str, Any]							=						np.array(UpperCamelCase__    ,       dtype=jnp.intaa		).reshape(UpperCamelCase__		)

    return output
def 							_lowerCamelCase(  UpperCamelCase__    : Dict    ,       UpperCamelCase__    : Optional[Any]=None		)		->  Dict:
    A       :       Union[str, Any]							=						ids_tensor(UpperCamelCase__    ,       vocab_size=2    ,       rng=UpperCamelCase__		)
    # make sure that at least one token is attended to for each batch
    A       :       Any							=						1
    return attn_mask


@require_flax
class   _lowercase						:
   _UpperCamelCase       		=   None
   _UpperCamelCase       		=   ()


   def 					snake_case				( self					):
       A,	A       :       Optional[int]							=						self.model_tester.prepare_config_and_inputs_for_common()

       # cut to half length & take max batch_size 3
       A       :       Dict							=						2
       A       :       List[str]							=						inputs['''input_ids'''].shape[-1] // 2
       A       :       int							=						inputs['''input_ids'''][:max_batch_size, :sequence_length]

       A       :       Optional[Any]							=						jnp.ones_like(_UpperCAmelCase					)
       A       :       int							=						attention_mask[:max_batch_size, :sequence_length]

       # generate max 5 tokens
       A       :       Optional[int]							=						input_ids.shape[-1] + 5
       if config.eos_token_id is not None and config.pad_token_id is None:
           # hack to allow generate for models such as GPT2 as is done in `generate()`
           A       :       str							=						config.eos_token_id
       return config, input_ids, attention_mask, max_length


   @is_pt_flax_cross_test
   def 					snake_case				( self					):
       A,	A,	A,	A       :       Optional[Any]							=						self._get_input_ids_and_config()
       A       :       Optional[int]							=						False
       A       :       Union[str, Any]							=						max_length
       A       :       str							=						0

       for model_class in self.all_generative_model_classes:
           A       :       int							=						model_class(_UpperCAmelCase					)

           A       :       Dict							=						model_class.__name__[4:]  # Skip the "Flax" at the beginning
           A       :       int							=						getattr(_UpperCAmelCase    ,   _UpperCAmelCase					)
           A       :       Union[str, Any]							=						pt_model_class(_UpperCAmelCase					).eval()
           A       :       Tuple							=						load_flax_weights_in_pytorch_model(_UpperCAmelCase    ,   flax_model.params					)

           A       :       Union[str, Any]							=						flax_model.generate(_UpperCAmelCase					).sequences
           A       :       Optional[int]							=						pt_model.generate(torch.tensor(_UpperCAmelCase    ,   dtype=torch.long					)					)

           if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
               A       :       List[Any]							=						flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

           self.assertListEqual(pt_generation_outputs.numpy().tolist()    ,   flax_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       str							=						self._get_input_ids_and_config()
       A       :       Optional[int]							=						False
       A       :       Dict							=						max_length

       for model_class in self.all_generative_model_classes:
           A       :       Any							=						model_class(_UpperCAmelCase					)

           A       :       Dict							=						model.generate(_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       str							=						jit(model.generate					)
           A       :       List[Any]							=						jit_generate(_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       List[Any]							=						self._get_input_ids_and_config()
       A       :       List[str]							=						True
       A       :       List[Any]							=						max_length

       for model_class in self.all_generative_model_classes:
           A       :       Any							=						model_class(_UpperCAmelCase					)

           A       :       Tuple							=						model.generate(_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       Tuple							=						jit(model.generate					)
           A       :       int							=						jit_generate(_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       List[str]							=						self._get_input_ids_and_config()
       A       :       Any							=						False
       A       :       str							=						max_length
       A       :       Optional[int]							=						2

       for model_class in self.all_generative_model_classes:
           A       :       Dict							=						model_class(_UpperCAmelCase					)

           A       :       Any							=						model.generate(_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       List[Any]							=						jit(model.generate					)
           A       :       Optional[Any]							=						jit_generate(_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       Optional[int]							=						self._get_input_ids_and_config()
       A       :       Dict							=						False
       A       :       List[Any]							=						max_length
       A       :       Optional[int]							=						2
       A       :       int							=						2

       for model_class in self.all_generative_model_classes:
           A       :       List[str]							=						model_class(_UpperCAmelCase					)

           A       :       List[str]							=						model.generate(_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[0]    ,   input_ids.shape[0] * config.num_return_sequences					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       List[Any]							=						self._get_input_ids_and_config()
       A       :       Any							=						True
       A       :       Any							=						max_length
       A       :       Any							=						0.8
       A       :       List[Any]							=						10
       A       :       List[Any]							=						0.3
       A       :       Union[str, Any]							=						1
       A       :       Any							=						8
       A       :       List[Any]							=						9

       for model_class in self.all_generative_model_classes:
           A       :       List[Any]							=						model_class(_UpperCAmelCase					)

           A       :       Any							=						model.generate(_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       int							=						jit(model.generate					)
           A       :       List[Any]							=						jit_generate(_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       Optional[Any]							=						self._get_input_ids_and_config()
       A       :       int							=						max_length
       A       :       Dict							=						1
       A       :       Tuple							=						8
       A       :       Optional[Any]							=						9

       for model_class in self.all_generative_model_classes:
           A       :       Dict							=						model_class(_UpperCAmelCase					)

           A       :       str							=						model.generate(_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       int							=						jit(model.generate					)
           A       :       Optional[int]							=						jit_generate(_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       int							=						self._get_input_ids_and_config()
       A       :       List[Any]							=						max_length
       A       :       Optional[Any]							=						2
       A       :       Tuple							=						1
       A       :       List[Any]							=						8
       A       :       Dict							=						9

       for model_class in self.all_generative_model_classes:
           A       :       Union[str, Any]							=						model_class(_UpperCAmelCase					)

           A       :       Any							=						model.generate(_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       Union[str, Any]							=						jit(model.generate					)
           A       :       int							=						jit_generate(_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       Dict							=						self._get_input_ids_and_config()

       # pad attention mask on the left
       A       :       Union[str, Any]							=						attention_mask.at[(0, 0)].set(0					)

       A       :       int							=						False
       A       :       List[Any]							=						max_length

       for model_class in self.all_generative_model_classes:
           A       :       List[str]							=						model_class(_UpperCAmelCase					)

           A       :       Dict							=						model.generate(_UpperCAmelCase    ,   attention_mask=_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       Dict							=						jit(model.generate					)
           A       :       Optional[Any]							=						jit_generate(_UpperCAmelCase    ,   attention_mask=_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       Optional[Any]							=						self._get_input_ids_and_config()

       # pad attention mask on the left
       A       :       Optional[Any]							=						attention_mask.at[(0, 0)].set(0					)

       A       :       Optional[int]							=						True
       A       :       int							=						max_length

       for model_class in self.all_generative_model_classes:
           A       :       int							=						model_class(_UpperCAmelCase					)

           A       :       Union[str, Any]							=						model.generate(_UpperCAmelCase    ,   attention_mask=_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       Optional[Any]							=						jit(model.generate					)
           A       :       Dict							=						jit_generate(_UpperCAmelCase    ,   attention_mask=_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)


   def 					snake_case				( self					):
       A,	A,	A,	A       :       Optional[Any]							=						self._get_input_ids_and_config()

       # pad attention mask on the left
       A       :       Optional[int]							=						attention_mask.at[(0, 0)].set(0					)

       A       :       Any							=						2
       A       :       Any							=						max_length

       for model_class in self.all_generative_model_classes:
           A       :       Dict							=						model_class(_UpperCAmelCase					)

           A       :       Optional[Any]							=						model.generate(_UpperCAmelCase    ,   attention_mask=_UpperCAmelCase					).sequences
           self.assertEqual(generation_outputs.shape[-1]    ,   _UpperCAmelCase					)

           A       :       str							=						jit(model.generate					)
           A       :       List[str]							=						jit_generate(_UpperCAmelCase    ,   attention_mask=_UpperCAmelCase					).sequences

           self.assertListEqual(generation_outputs.tolist()    ,   jit_generation_outputs.tolist()					)







@require_flax
class   _lowercase						(							unittest.TestCase				):


   def 					snake_case				( self					):
       A       :       List[Any]							=						AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert'''					)
       A       :       Dict							=						FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''					)

       A       :       Union[str, Any]							=						'''Hello world'''
       A       :       Union[str, Any]							=						tokenizer(_UpperCAmelCase    ,   return_tensors='''np'''					).input_ids

       # typos are quickly detected (the correct argument is `do_sample`)
       with self.assertRaisesRegex(_UpperCAmelCase    ,   '''do_samples'''					):
           model.generate(_UpperCAmelCase    ,   do_samples=_UpperCAmelCase					)

       # arbitrary arguments that will not be used anywhere are also not accepted
       with self.assertRaisesRegex(_UpperCAmelCase    ,   '''foo'''					):
           A       :       List[Any]							=						{'''foo''': '''bar'''}
           model.generate(_UpperCAmelCase    ,   **_UpperCAmelCase					)
