


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

import os
from pathlib import Path





def 	_lowerCAmelCase       (    _lowerCAmelCase      ,	_lowerCAmelCase      ,	_lowerCAmelCase )						->	List[Any]:


						'''simple docstring'''






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

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

						__snake_case				=		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(_lowerCAmelCase      ,	exist_ok=_lowerCAmelCase )
						__snake_case				=		os.path.join(_lowerCAmelCase      ,	"README.md" )
						print(F'''Generating {path}''' )
						with open(_lowerCAmelCase      ,	"w"      ,	encoding="utf-8" ) as f:
												f.write(_lowerCAmelCase )


# make sure we are under the root of the project
A							:					List[str]     						=     Path(__file__).resolve().parent.parent.parent
A							:					Optional[Any]     						=     repo_dir / 'model_cards'

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









import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
	import onnxruntime as ort






class     UpperCamelCase(  _a     ,							unittest.TestCase   ):
					# TODO: is there an appropriate internal test set?
					snake_case_		:				Dict										=	"""ssube/stable-diffusion-x4-upscaler-onnx"""


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Dict     ,    SCREAMING_SNAKE_CASE	:		List[str]=0						)			->	Union[str, Any]:




											'''simple docstring'''

											__snake_case				=		floats_tensor((1, 3, 1_2_8, 1_2_8)     ,    rng=random.Random(SCREAMING_SNAKE_CASE						)						)
											__snake_case				=		torch.manual_seed(SCREAMING_SNAKE_CASE						)
											__snake_case				=		{
											    "prompt": "A painting of a squirrel eating a burger",
											    "image": image,
											    "generator": generator,
											    "num_inference_steps": 3,
											    "guidance_scale": 7.5,
											    "output_type": "numpy",
											}
											return inputs


					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[str]						)			->	List[str]:




											'''simple docstring'''

											__snake_case				=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,    provider="CPUExecutionProvider"						)
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		self.get_dummy_inputs()
											__snake_case				=		pipe(**SCREAMING_SNAKE_CASE						).images
											__snake_case				=		image[0, -3:, -3:, -1].flatten()

											# started as 128, should now be 512
											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											__snake_case				=		np.array(
											    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]						)
											assert np.abs(image_slice - expected_slice						).max() < 1e-1


					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[str]						)			->	Optional[Any]:




											'''simple docstring'''

											__snake_case				=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,    provider="CPUExecutionProvider"						)
											__snake_case				=		PNDMScheduler.from_config(pipe.scheduler.config     ,    skip_prk_steps=SCREAMING_SNAKE_CASE						)
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		self.get_dummy_inputs()
											__snake_case				=		pipe(**SCREAMING_SNAKE_CASE						).images
											__snake_case				=		image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											__snake_case				=		np.array(
											    [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]						)
											assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Any						)			->	Optional[int]:




											'''simple docstring'''

											__snake_case				=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,    provider="CPUExecutionProvider"						)
											__snake_case				=		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		self.get_dummy_inputs()
											__snake_case				=		pipe(**SCREAMING_SNAKE_CASE						).images
											__snake_case				=		image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											__snake_case				=		np.array(
											    [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]						)

											assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Dict						)			->	Dict:




											'''simple docstring'''

											__snake_case				=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,    provider="CPUExecutionProvider"						)
											__snake_case				=		EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		self.get_dummy_inputs()
											__snake_case				=		pipe(**SCREAMING_SNAKE_CASE						).images
											__snake_case				=		image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											__snake_case				=		np.array(
											    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]						)
											assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1






					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[Any]						)			->	List[str]:




											'''simple docstring'''

											__snake_case				=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,    provider="CPUExecutionProvider"						)
											__snake_case				=		EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		self.get_dummy_inputs()
											__snake_case				=		pipe(**SCREAMING_SNAKE_CASE						).images
											__snake_case				=		image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											__snake_case				=		np.array(
											    [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]						)

											assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1






@nightly
@require_onnxruntime
@require_torch_gpu
class     UpperCamelCase(  unittest.TestCase   ):


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		str						)			->	List[Any]:




											'''simple docstring'''

											return (
											    "CUDAExecutionProvider",
											    {
											        "gpu_mem_limit": "15000000000",  # 15GB
											        "arena_extend_strategy": "kSameAsRequested",
											    },
											)


					@property
					def 							SCREAMING_SNAKE_CASE_  (						self	:		Tuple						)			->	Tuple:




											'''simple docstring'''

											__snake_case				=		ort.SessionOptions()
											__snake_case				=		False
											return options


					def 							SCREAMING_SNAKE_CASE_  (						self	:		int						)			->	Optional[int]:




											'''simple docstring'''

											__snake_case				=		load_image(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
											    "/img2img/sketch-mountains-input.jpg"						)
											__snake_case				=		init_image.resize((1_2_8, 1_2_8)						)
											# using the PNDM scheduler by default
											__snake_case				=		OnnxStableDiffusionUpscalePipeline.from_pretrained(
											    "ssube/stable-diffusion-x4-upscaler-onnx"     ,    provider=self.gpu_provider     ,    sess_options=self.gpu_options     ,    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		"A fantasy landscape, trending on artstation"

											__snake_case				=		torch.manual_seed(0						)
											__snake_case				=		pipe(
											    prompt=SCREAMING_SNAKE_CASE     ,    image=SCREAMING_SNAKE_CASE     ,    guidance_scale=7.5     ,    num_inference_steps=1_0     ,    generator=SCREAMING_SNAKE_CASE     ,    output_type="np"     ,    )
											__snake_case				=		output.images
											__snake_case				=		images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

											assert images.shape == (1, 5_1_2, 5_1_2, 3)
											__snake_case				=		np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]						)
											# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

											assert np.abs(image_slice.flatten() - expected_slice						).max() < 2e-2






					def 							SCREAMING_SNAKE_CASE_  (						self	:		Tuple						)			->	Optional[int]:




											'''simple docstring'''

											__snake_case				=		load_image(
											    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
											    "/img2img/sketch-mountains-input.jpg"						)
											__snake_case				=		init_image.resize((1_2_8, 1_2_8)						)
											__snake_case				=		LMSDiscreteScheduler.from_pretrained(
											    "ssube/stable-diffusion-x4-upscaler-onnx"     ,    subfolder="scheduler"						)
											__snake_case				=		OnnxStableDiffusionUpscalePipeline.from_pretrained(
											    "ssube/stable-diffusion-x4-upscaler-onnx"     ,    scheduler=SCREAMING_SNAKE_CASE     ,    provider=self.gpu_provider     ,    sess_options=self.gpu_options     ,    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE						)

											__snake_case				=		"A fantasy landscape, trending on artstation"

											__snake_case				=		torch.manual_seed(0						)
											__snake_case				=		pipe(
											    prompt=SCREAMING_SNAKE_CASE     ,    image=SCREAMING_SNAKE_CASE     ,    guidance_scale=7.5     ,    num_inference_steps=2_0     ,    generator=SCREAMING_SNAKE_CASE     ,    output_type="np"     ,    )
											__snake_case				=		output.images
											__snake_case				=		images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

											assert images.shape == (1, 5_1_2, 5_1_2, 3)
											__snake_case				=		np.array(
											    [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]						)
											# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

											assert np.abs(image_slice.flatten() - expected_slice						).max() < 2e-2





