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

import os
from pathlib import Path



def lowerCamelCase  (       SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    __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(SCREAMING_SNAKE_CASE  ,      exist_ok=SCREAMING_SNAKE_CASE     )
    __UpperCamelCase					:Union[str, Any]        =		os.path.join(SCREAMING_SNAKE_CASE  ,      '''README.md'''     )
    print(f"""Generating {path}"""     )
    with open(SCREAMING_SNAKE_CASE  ,      '''w'''  ,      encoding='''utf-8'''     ) as f:
        f.write(SCREAMING_SNAKE_CASE     )


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






import json
import os
import tempfile
from unittest.mock import patch

import torch
from torch.utils.data import DataLoader, TensorDataset

from accelerate import DistributedType, infer_auto_device_map, init_empty_weights
from accelerate.accelerator import Accelerator
from accelerate.state import GradientState, PartialState
from accelerate.test_utils import require_bnb, require_multi_gpu, slow
from accelerate.test_utils.testing import AccelerateTestCase, require_cuda
from accelerate.utils import patch_environment



def lowerCamelCase  (       ):
    '''simple docstring'''







    __UpperCamelCase					:List[str]        =		torch.nn.Linear(2  ,      4     )
    __UpperCamelCase					:Any        =		torch.optim.AdamW(model.parameters()  ,      lr=1.0     )
    __UpperCamelCase					:List[Any]        =		torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE  ,      max_lr=0.01  ,      steps_per_epoch=2  ,      epochs=1     )
    __UpperCamelCase					:List[Any]        =		DataLoader(TensorDataset(torch.tensor([1, 2, 3]     )     )     )
    __UpperCamelCase					:Dict        =		DataLoader(TensorDataset(torch.tensor([4, 5, 6]     )     )     )

    return model, optimizer, scheduler, train_dl, valid_dl



def lowerCamelCase  (       SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    return (model.weight.abs().sum() + model.bias.abs().sum()).item()



def lowerCamelCase  (       SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    __UpperCamelCase					:Union[str, Any]        =		torch.nn.Linear(*tuple(model.weight.T.shape     )     ).state_dict()
    model.load_state_dict(SCREAMING_SNAKE_CASE     )


class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    @require_cuda
    def       UpperCamelCase__       (     self)	->     Dict:
        __UpperCamelCase					:Dict        =		Accelerator()
        assert PartialState._shared_state["_cpu"] is False
        assert PartialState._shared_state["device"].type == "cuda"
        with self.assertRaises(__lowercase):
            __UpperCamelCase					:Any        =		Accelerator(cpu=__lowercase)







    def       UpperCamelCase__       (     self)	->     Any:
        __UpperCamelCase					:List[Any]        =		Accelerator()
        __UpperCamelCase					:List[Any]        =		GradientState()
        assert state.num_steps == 1
        __UpperCamelCase					:Any        =		4
        assert state.num_steps == 4

        assert state.sync_gradients is True
        __UpperCamelCase					:int        =		False
        assert state.sync_gradients is False
        GradientState._reset_state()







    def       UpperCamelCase__       (     self)	->     Dict:
        __UpperCamelCase					:Tuple        =		Accelerator()
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:Optional[Any]        =		create_components()

        (
            (
            __UpperCamelCase
        )  ,	(
            __UpperCamelCase
        )  ,	(
            __UpperCamelCase
        )  ,	(
            __UpperCamelCase
        )  ,	(
            __UpperCamelCase
        )  ,	
        )					:int        =		accelerator.prepare(__lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase)

        self.assertTrue(prepared_model in accelerator._models)
        self.assertTrue(prepared_optimizer in accelerator._optimizers)
        self.assertTrue(prepared_scheduler in accelerator._schedulers)
        self.assertTrue(prepared_train_dl in accelerator._dataloaders)
        self.assertTrue(prepared_valid_dl in accelerator._dataloaders)







    def       UpperCamelCase__       (     self)	->     Optional[Any]:
        __UpperCamelCase					:str        =		Accelerator()
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:Optional[Any]        =		create_components()
        accelerator.prepare(__lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase)
        accelerator.free_memory()

        self.assertTrue(len(accelerator._models) == 0)
        self.assertTrue(len(accelerator._optimizers) == 0)
        self.assertTrue(len(accelerator._schedulers) == 0)
        self.assertTrue(len(accelerator._dataloaders) == 0)







    def       UpperCamelCase__       (     self)	->     Union[str, Any]:
        PartialState._reset_state()

        # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist
        def noop(*__lowercase			,			**__lowercase):
            pass

        with patch('''torch.cuda.set_device'''			,			__lowercase), patch_environment(ACCELERATE_TORCH_DEVICE='''cuda:64'''):
            __UpperCamelCase					:Optional[Any]        =		Accelerator()
            self.assertEqual(str(accelerator.state.device)			,			'''cuda:64''')







    def       UpperCamelCase__       (     self)	->     List[Any]:
        __UpperCamelCase					:List[Any]        =		Accelerator()
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:List[Any]        =		create_components()
        accelerator.prepare(__lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase)

        __UpperCamelCase					:Tuple        =		get_signature(__lowercase)

        with tempfile.TemporaryDirectory() as tmpdirname:
            accelerator.save_state(__lowercase)

            # make sure random weights don't match
            load_random_weights(__lowercase)
            self.assertTrue(abs(model_signature - get_signature(__lowercase)) > 1E-3)

            # make sure loaded weights match
            accelerator.load_state(__lowercase)
            self.assertTrue(abs(model_signature - get_signature(__lowercase)) < 1E-3)







    def       UpperCamelCase__       (     self)	->     Dict:
        __UpperCamelCase					:List[Any]        =		Accelerator()
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:Any        =		create_components()
        accelerator.prepare(__lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase)

        __UpperCamelCase					:Any        =		get_signature(__lowercase)

        # saving hook
        def save_config(__lowercase			,			__lowercase			,			__lowercase):
            __UpperCamelCase					:Union[str, Any]        =		{'''class_name''': models[0].__class__.__name__}

            with open(os.path.join(__lowercase			,			'''data.json''')			,			'''w''') as f:
                json.dump(__lowercase			,			__lowercase)

        # loading hook
        def load_config(__lowercase			,			__lowercase):
            with open(os.path.join(__lowercase			,			'''data.json''')			,			'''r''') as f:
                __UpperCamelCase					:Dict        =		json.load(__lowercase)

            __UpperCamelCase					:Dict        =		config['''class_name''']

        __UpperCamelCase					:Union[str, Any]        =		accelerator.register_save_state_pre_hook(__lowercase)
        __UpperCamelCase					:Any        =		accelerator.register_load_state_pre_hook(__lowercase)

        with tempfile.TemporaryDirectory() as tmpdirname:
            accelerator.save_state(__lowercase)

            # make sure random weights don't match with hooks
            load_random_weights(__lowercase)
            self.assertTrue(abs(model_signature - get_signature(__lowercase)) > 1E-3)

            # random class name to verify correct one is loaded
            __UpperCamelCase					:int        =		'''random'''

            # make sure loaded weights match with hooks
            accelerator.load_state(__lowercase)
            self.assertTrue(abs(model_signature - get_signature(__lowercase)) < 1E-3)

            # mode.class_name is loaded from config
            self.assertTrue(model.class_name == model.__class__.__name__)

        # remove hooks
        save_hook.remove()
        load_hook.remove()

        with tempfile.TemporaryDirectory() as tmpdirname:
            accelerator.save_state(__lowercase)

            # make sure random weights don't match with hooks removed
            load_random_weights(__lowercase)
            self.assertTrue(abs(model_signature - get_signature(__lowercase)) > 1E-3)

            # random class name to verify correct one is loaded
            __UpperCamelCase					:Dict        =		'''random'''

            # make sure loaded weights match with hooks removed
            accelerator.load_state(__lowercase)
            self.assertTrue(abs(model_signature - get_signature(__lowercase)) < 1E-3)

            # mode.class_name is NOT loaded from config
            self.assertTrue(model.class_name != model.__class__.__name__)







    def       UpperCamelCase__       (     self)	->     Dict:
        __UpperCamelCase					:Optional[Any]        =		Accelerator()
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:Union[str, Any]        =		create_components()
        __UpperCamelCase					:Optional[Any]        =		None

        # This should work
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:List[Any]        =		accelerator.prepare(
            __lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase)
        self.assertTrue(dummy_obj is None)







    def       UpperCamelCase__       (     self)	->     List[str]:
        __UpperCamelCase					:List[str]        =		Accelerator()
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:Any        =		create_components()
        __UpperCamelCase					:Dict        =		[1, 2, 3]

        # This should work
        __UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase  ,	__UpperCamelCase					:Tuple        =		accelerator.prepare(
            __lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase)
        self.assertEqual(
            getattr(__lowercase			,			'''_is_accelerate_prepared'''			,			__lowercase)			,			__lowercase			,			'''Dummy object should have `_is_accelerate_prepared` set to `True`'''			,			)
        self.assertEqual(
            getattr(__lowercase			,			'''_is_accelerate_prepared'''			,			__lowercase)			,			__lowercase			,			'''Model is missing `_is_accelerator_prepared` or is set to `False`'''			,			)
        self.assertEqual(
            getattr(__lowercase			,			'''_is_accelerate_prepared'''			,			__lowercase)			,			__lowercase			,			'''Optimizer is missing `_is_accelerator_prepared` or is set to `False`'''			,			)
        self.assertEqual(
            getattr(__lowercase			,			'''_is_accelerate_prepared'''			,			__lowercase)			,			__lowercase			,			'''Scheduler is missing `_is_accelerator_prepared` or is set to `False`'''			,			)
        self.assertEqual(
            getattr(__lowercase			,			'''_is_accelerate_prepared'''			,			__lowercase)			,			__lowercase			,			'''Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`'''			,			)
        self.assertEqual(
            getattr(__lowercase			,			'''_is_accelerate_prepared'''			,			__lowercase)			,			__lowercase			,			'''Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`'''			,			)







    @slow
    @require_bnb
    def       UpperCamelCase__       (     self)	->     int:
        from transformers import AutoModelForCausalLM

        __UpperCamelCase					:Optional[int]        =		AutoModelForCausalLM.from_pretrained(
            '''EleutherAI/gpt-neo-125m'''			,			load_in_abit=__lowercase			,			device_map={'''''': 0}			,			)
        __UpperCamelCase					:Optional[Any]        =		Accelerator()

        # This should work
        __UpperCamelCase					:int        =		accelerator.prepare(__lowercase)







    @slow
    @require_bnb
    def       UpperCamelCase__       (     self)	->     List[str]:
        from transformers import AutoModelForCausalLM

        __UpperCamelCase					:str        =		Accelerator()

        with init_empty_weights():
            __UpperCamelCase					:List[Any]        =		AutoModelForCausalLM.from_pretrained(
                '''EleutherAI/gpt-neo-125m'''			,			)
            model.tie_weights()
            __UpperCamelCase					:List[str]        =		infer_auto_device_map(__lowercase)
            __UpperCamelCase					:str        =		'''cpu'''

        __UpperCamelCase					:List[Any]        =		AutoModelForCausalLM.from_pretrained(
            '''EleutherAI/gpt-neo-125m'''			,			device_map=__lowercase			,			load_in_abit=__lowercase			,			llm_inta_enable_fpaa_cpu_offload=__lowercase)

        # This should not work and get value error
        with self.assertRaises(__lowercase):
            __UpperCamelCase					:Union[str, Any]        =		accelerator.prepare(__lowercase)







    @slow
    @require_bnb
    @require_multi_gpu
    def       UpperCamelCase__       (     self)	->     Union[str, Any]:
        from transformers import AutoModelForCausalLM

        __UpperCamelCase					:int        =		{'''distributed_type''': DistributedType.MULTI_GPU}

        with init_empty_weights():
            __UpperCamelCase					:Tuple        =		AutoModelForCausalLM.from_pretrained(
                '''EleutherAI/gpt-neo-125m'''			,			)
            model.tie_weights()
            __UpperCamelCase					:int        =		infer_auto_device_map(__lowercase)
            __UpperCamelCase					:List[Any]        =		1

        __UpperCamelCase					:int        =		AutoModelForCausalLM.from_pretrained(
            '''EleutherAI/gpt-neo-125m'''			,			load_in_abit=__lowercase			,			device_map=__lowercase			,			)
        __UpperCamelCase					:Dict        =		Accelerator()

        # This should not work and get value error
        with self.assertRaises(__lowercase):
            __UpperCamelCase					:Any        =		accelerator.prepare(__lowercase)

        PartialState._reset_state()







    @slow
    @require_bnb
    @require_multi_gpu
    def       UpperCamelCase__       (     self)	->     Dict:
        from transformers import AutoModelForCausalLM

        with init_empty_weights():
            __UpperCamelCase					:Optional[int]        =		AutoModelForCausalLM.from_pretrained(
                '''EleutherAI/gpt-neo-125m'''			,			)
            __UpperCamelCase					:List[str]        =		infer_auto_device_map(__lowercase)
            __UpperCamelCase					:Optional[int]        =		1

        __UpperCamelCase					:Optional[int]        =		AutoModelForCausalLM.from_pretrained(
            '''EleutherAI/gpt-neo-125m'''			,			load_in_abit=__lowercase			,			device_map=__lowercase			,			)
        __UpperCamelCase					:int        =		Accelerator()

        # This should work
        __UpperCamelCase					:int        =		accelerator.prepare(__lowercase)







    @require_cuda
    def       UpperCamelCase__       (     self)	->     int:
        __UpperCamelCase					:Tuple        =		torch.nn.Linear(10			,			10)
        __UpperCamelCase					:Optional[Any]        =		torch.optim.SGD(model.parameters()			,			lr=0.01)
        __UpperCamelCase					:Any        =		Accelerator(cpu=__lowercase)
        __UpperCamelCase					:Tuple        =		accelerator.prepare(__lowercase)





