# Usage:
# ./gen-card-allenai-wmt16.py

import os
from pathlib import Path







def     _a				(      lowercase__  :			Any     ,  lowercase__  :			Optional[Any]     ,  lowercase__  :			List[Any]     ,  lowercase__  :			Optional[int] ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		{
         'en': 'Machine learning is great, isn\'t it?',
         'ru': 'Машинное обучение - это здорово, не так ли?',
         'de': 'Maschinelles Lernen ist großartig, nicht wahr?',
     }

     # BLUE scores as follows:
     # "pair": [fairseq, transformers]
     SCREAMING_SNAKE_CASE__				:				str			=		{
         'wmt16-en-de-dist-12-1': [28.3, 27.52],
         'wmt16-en-de-dist-6-1': [27.4, 27.11],
         'wmt16-en-de-12-1': [26.9, 25.75],
     }
     SCREAMING_SNAKE_CASE__				:				Dict			=		f'''{src_lang}-{tgt_lang}'''

     SCREAMING_SNAKE_CASE__				:				Tuple			=		f'''
---
language:
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt16
- allenai
license: apache-2.0
datasets:
- wmt16
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.

For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).

All 3 models are available:

* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)
* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)
* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)


## Intended uses & limitations

#### How to use

```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = "allenai/{model_name}"
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


## Training data

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

## Eval results

Here are the BLEU scores:

model   | fairseq | transformers
-------|---------|----------
{model_name}  | {scores[model_name][0]} | {scores[model_name][1]}

The score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.

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=5
mkdir -p $DATA_DIR
sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source
sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target
echo $PAIR
PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $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
```

## Data Sources

- [training, etc.](http://www.statmt.org/wmt16/)
- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)


### BibTeX entry and citation info

```
@misc{{kasai2020deep,
    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},
    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},
    year={{2020}},
    eprint={{2006.10369}},
    archivePrefix={{arXiv}},
    primaryClass={{cs.CL}}
}}
```

'''
     model_card_dir.mkdir(parents=lowercase__     ,  exist_ok=lowercase__ )
     SCREAMING_SNAKE_CASE__				:				Optional[int]			=		os.path.join(lowercase__     ,  'README.md' )
     print(f'''Generating {path}''' )
     with open(lowercase__     ,  'w'     ,  encoding='utf-8' ) as f:
          f.write(lowercase__ )


# make sure we are under the root of the project
SCREAMING_SNAKE_CASE__		:					str						=					Path(__file__).resolve().parent.parent.parent
SCREAMING_SNAKE_CASE__		:					Any						=					repo_dir / "model_cards"

for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]:
      SCREAMING_SNAKE_CASE__		:					Tuple						=					model_cards_dir / "allenai" / model_name
      write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)




import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

      from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
      SCREAMING_SNAKE_CASE__		:					Any						=					False

if is_vision_available():
      from PIL import Image

      from transformers import PixaStructImageProcessor

class       snake_case					(      unittest.TestCase						):




  def __init__(      self     :	List[Any]     , a_     :	Optional[int]     , a_     :	Dict=7     , a_     :	Any=3     , a_     :	Any=18     , a_     :	int=30     , a_     :	int=400     , a_     :	List[Any]=None     , a_     :	int=True     , a_     :	int=True     , a_     :	Dict=None     , )->       Optional[int]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		size if size is not None else {'height': 20, 'width': 20}
       SCREAMING_SNAKE_CASE__				:				str			=		parent
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		batch_size
       SCREAMING_SNAKE_CASE__				:				Any			=		num_channels
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		image_size
       SCREAMING_SNAKE_CASE__				:				List[str]			=		min_resolution
       SCREAMING_SNAKE_CASE__				:				Dict			=		max_resolution
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		size
       SCREAMING_SNAKE_CASE__				:				Tuple			=		do_normalize
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		do_convert_rgb
       SCREAMING_SNAKE_CASE__				:				List[str]			=		[512, 1024, 2048, 4096]
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		patch_size if patch_size is not None else {'height': 16, 'width': 16}




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




       """simple docstring"""
       return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}




  def 	__lowercase(      self     :	Dict				)->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
       SCREAMING_SNAKE_CASE__				:				str			=		Image.open(requests.get(a_     , stream=a_				).raw				).convert('RGB'				)
       return raw_image




@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11   ,						reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'   ,						)
@require_torch
@require_vision
class       snake_case					(      UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     PixaStructImageProcessor if is_vision_available() else None




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		PixaStructImageProcessingTester(self				)




  @property
  def 	__lowercase(      self     :	Dict				)->       Tuple:




       """simple docstring"""
       return self.image_processor_tester.prepare_image_processor_dict()




  def 	__lowercase(      self     :	Any				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.image_processing_class(**self.image_processor_dict				)
       self.assertTrue(hasattr(a_     , 'do_normalize'				)				)
       self.assertTrue(hasattr(a_     , 'do_convert_rgb'				)				)




  def 	__lowercase(      self     :	List[Any]				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.image_processor_tester.prepare_dummy_image()

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.image_processing_class(**self.image_processor_dict				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		2048

       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		image_processor(a_     , return_tensors='pt'     , max_patches=a_				)
       self.assertTrue(torch.allclose(inputs.flattened_patches.mean()     , torch.tensor(0.0606				)     , atol=1e-3     , rtol=1e-3				)				)




  def 	__lowercase(      self     :	Any				)->       Tuple:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PIL images
       SCREAMING_SNAKE_CASE__				:				Dict			=		prepare_image_inputs(self.image_processor_tester     , equal_resolution=a_				)
       for image in image_inputs:
            self.assertIsInstance(a_     , Image.Image				)

       # Test not batched input
       SCREAMING_SNAKE_CASE__				:				str			=		(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            SCREAMING_SNAKE_CASE__				:				List[str]			=		image_processor(
                image_inputs[0]     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (1, max_patch, expected_hidden_dim)     , )

            # Test batched
            SCREAMING_SNAKE_CASE__				:				Tuple			=		image_processor(
                a_     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)     , )




  def 	__lowercase(      self     :	Any				)->       Any:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Tuple			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PIL images
       SCREAMING_SNAKE_CASE__				:				Dict			=		prepare_image_inputs(self.image_processor_tester     , equal_resolution=a_				)
       for image in image_inputs:
            self.assertIsInstance(a_     , Image.Image				)

       # Test not batched input
       SCREAMING_SNAKE_CASE__				:				str			=		(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       SCREAMING_SNAKE_CASE__				:				int			=		True

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            with self.assertRaises(a_				):
                 SCREAMING_SNAKE_CASE__				:				Dict			=		image_processor(
                     image_inputs[0]     , return_tensors='pt'     , max_patches=a_				).flattened_patches

            SCREAMING_SNAKE_CASE__				:				List[Any]			=		'Hello'

            SCREAMING_SNAKE_CASE__				:				List[Any]			=		image_processor(
                image_inputs[0]     , return_tensors='pt'     , max_patches=a_     , header_text=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (1, max_patch, expected_hidden_dim)     , )

            # Test batched
            SCREAMING_SNAKE_CASE__				:				Any			=		image_processor(
                a_     , return_tensors='pt'     , max_patches=a_     , header_text=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)     , )




  def 	__lowercase(      self     :	List[Any]				)->       Dict:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.image_processing_class(**self.image_processor_dict				)
       # create random numpy tensors
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		prepare_image_inputs(self.image_processor_tester     , equal_resolution=a_     , numpify=a_				)
       for image in image_inputs:
            self.assertIsInstance(a_     , np.ndarray				)

       SCREAMING_SNAKE_CASE__				:				str			=		(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            SCREAMING_SNAKE_CASE__				:				str			=		image_processor(
                image_inputs[0]     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (1, max_patch, expected_hidden_dim)     , )

            # Test batched
            SCREAMING_SNAKE_CASE__				:				int			=		image_processor(
                a_     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)     , )




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




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Any			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PyTorch tensors
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		prepare_image_inputs(self.image_processor_tester     , equal_resolution=a_     , torchify=a_				)
       for image in image_inputs:
            self.assertIsInstance(a_     , torch.Tensor				)

       # Test not batched input
       SCREAMING_SNAKE_CASE__				:				Any			=		(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		image_processor(
                image_inputs[0]     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (1, max_patch, expected_hidden_dim)     , )

            # Test batched
            SCREAMING_SNAKE_CASE__				:				List[Any]			=		image_processor(
                a_     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)     , )




@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11   ,						reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'   ,						)
@require_torch
@require_vision
class       snake_case					(      UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     PixaStructImageProcessor if is_vision_available() else None




  def 	__lowercase(      self     :	Union[str, Any]				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		PixaStructImageProcessingTester(self     , num_channels=4				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		3




  @property
  def 	__lowercase(      self     :	Any				)->       Any:




       """simple docstring"""
       return self.image_processor_tester.prepare_image_processor_dict()




  def 	__lowercase(      self     :	Dict				)->       Optional[int]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		self.image_processing_class(**self.image_processor_dict				)
       self.assertTrue(hasattr(a_     , 'do_normalize'				)				)
       self.assertTrue(hasattr(a_     , 'do_convert_rgb'				)				)




  def 	__lowercase(      self     :	str				)->       Union[str, Any]:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				str			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PIL images
       SCREAMING_SNAKE_CASE__				:				Tuple			=		prepare_image_inputs(self.image_processor_tester     , equal_resolution=a_				)
       for image in image_inputs:
            self.assertIsInstance(a_     , Image.Image				)

       # Test not batched input
       SCREAMING_SNAKE_CASE__				:				Dict			=		(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * (self.image_processor_tester.num_channels - 1)
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
            # Test not batched input
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		image_processor(
                image_inputs[0]     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (1, max_patch, expected_hidden_dim)     , )

            # Test batched
            SCREAMING_SNAKE_CASE__				:				Tuple			=		image_processor(
                a_     , return_tensors='pt'     , max_patches=a_				).flattened_patches
            self.assertEqual(
                encoded_images.shape     , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)     , )



