



"""simple docstring"""
# Usage:
# ./gen-card-allenai-wmt16.py

import os
from pathlib import Path



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__	)			->      int:
		a_     :      List[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]
		a_     :      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],
		}
		a_     :      Dict 						=     F"""{src_lang}-{tgt_lang}"""

		a_     :      Optional[Any] 						=     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=SCREAMING_SNAKE_CASE__, exist_ok=SCREAMING_SNAKE_CASE__	)
		a_     :      str 						=     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
SCREAMING_SNAKE_CASE_				= Path(__file__).resolve().parent.parent.parent
SCREAMING_SNAKE_CASE_				= 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_				= model_cards_dir / """allenai""" / model_name
					write_model_card(model_card_dir, src_lang="""en""", tgt_lang="""de""", model_name=model_name)




"""simple docstring"""
import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
					import torch

if is_datasets_available():
					from datasets import load_dataset

SCREAMING_SNAKE_CASE_				= random.Random()



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__=1.0, SCREAMING_SNAKE_CASE__=None, SCREAMING_SNAKE_CASE__=None	)			->      Tuple:
		if rng is None:
				a_     :      Any 						=     global_rng

		a_     :      Dict 						=     []
		for batch_idx in range(shape[0]	):
				values.append([]	)
				for _ in range(shape[1]	):
						values[-1].append(rng.random() * scale	)

		return values




class 			snake_case_						(						unittest.TestCase				):






							def __init__(   self			,     a_			,     a_=7			,     a_=4_0_0			,     a_=2_0_0_0			,     a_=2_0_4_8			,     a_=1_2_8			,     a_=1			,     a_=5_1_2			,     a_=3_0			,     a_=4_4_1_0_0			,     ):
									a_     :      Optional[Any] 						=     parent
									a_     :      Tuple 						=     batch_size
									a_     :      Union[str, Any] 						=     min_seq_length
									a_     :      Dict 						=     max_seq_length
									a_     :      Union[str, Any] 						=     (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									a_     :      int 						=     spectrogram_length
									a_     :      Optional[Any] 						=     feature_size
									a_     :      Optional[int] 						=     num_audio_channels
									a_     :      List[str] 						=     hop_length
									a_     :      Optional[int] 						=     chunk_length
									a_     :      List[str] 						=     sampling_rate






							def snake_case_  (   self      ):
									return {
									    "spectrogram_length": self.spectrogram_length,
									    "feature_size": self.feature_size,
									    "num_audio_channels": self.num_audio_channels,
									    "hop_length": self.hop_length,
									    "chunk_length": self.chunk_length,
									    "sampling_rate": self.sampling_rate,
									}






							def snake_case_  (   self			,     a_=False			,     a_=False      ):
									def _flatten(a_      ):
											return list(itertools.chain(*a_      )      )

									if equal_length:
											a_     :      Tuple 						=     [floats_list((self.max_seq_length, self.feature_size)      ) for _ in range(self.batch_size      )]
									else:
											# make sure that inputs increase in size
											a_     :      Optional[Any] 						=     [
											    floats_list((x, self.feature_size)      )
											    for x in range(self.min_seq_length			,     self.max_seq_length			,     self.seq_length_diff      )
											]
									if numpify:
											a_     :      Tuple 						=     [np.asarray(a_      ) for x in speech_inputs]
									return speech_inputs




@require_torch
@require_torchaudio
class 			snake_case_						(						a_     ,unittest.TestCase				):
							__lowerCAmelCase    					=					TvltFeatureExtractor






							def snake_case_  (   self      ):
									a_     :      Dict 						=     TvltFeatureExtractionTester(self      )






							def snake_case_  (   self      ):
									a_     :      Optional[Any] 						=     self.feature_extraction_class(**self.feat_extract_dict      )
									self.assertTrue(hasattr(a_			,     "spectrogram_length"      )      )
									self.assertTrue(hasattr(a_			,     "feature_size"      )      )
									self.assertTrue(hasattr(a_			,     "num_audio_channels"      )      )
									self.assertTrue(hasattr(a_			,     "hop_length"      )      )
									self.assertTrue(hasattr(a_			,     "chunk_length"      )      )
									self.assertTrue(hasattr(a_			,     "sampling_rate"      )      )






							def snake_case_  (   self      ):
									a_     :      List[Any] 						=     self.feature_extraction_class(**self.feat_extract_dict      )

									with tempfile.TemporaryDirectory() as tmpdirname:
											a_     :      List[Any] 						=     feat_extract_first.save_pretrained(a_      )[0]
											check_json_file_has_correct_format(a_      )
											a_     :      Tuple 						=     self.feature_extraction_class.from_pretrained(a_      )

									a_     :      Dict 						=     feat_extract_first.to_dict()
									a_     :      List[str] 						=     feat_extract_second.to_dict()
									a_     :      List[Any] 						=     dict_first.pop("mel_filters"      )
									a_     :      str 						=     dict_second.pop("mel_filters"      )
									self.assertTrue(np.allclose(a_			,     a_      )      )
									self.assertEqual(a_			,     a_      )






							def snake_case_  (   self      ):
									a_     :      List[str] 						=     self.feature_extraction_class(**self.feat_extract_dict      )

									with tempfile.TemporaryDirectory() as tmpdirname:
											a_     :      Dict 						=     os.path.join(a_			,     "feat_extract.json"      )
											feat_extract_first.to_json_file(a_      )
											a_     :      str 						=     self.feature_extraction_class.from_json_file(a_      )

									a_     :      Dict 						=     feat_extract_first.to_dict()
									a_     :      str 						=     feat_extract_second.to_dict()
									a_     :      int 						=     dict_first.pop("mel_filters"      )
									a_     :      List[Any] 						=     dict_second.pop("mel_filters"      )
									self.assertTrue(np.allclose(a_			,     a_      )      )
									self.assertEqual(a_			,     a_      )






							def snake_case_  (   self      ):
									# Initialize feature_extractor
									a_     :      str 						=     self.feature_extraction_class(**self.feat_extract_dict      )

									# create three inputs of length 800, 1000, and 1200
									a_     :      Optional[Any] 						=     [floats_list((1, x)      )[0] for x in range(8_0_0			,     1_4_0_0			,     2_0_0      )]
									a_     :      Union[str, Any] 						=     [np.asarray(a_      ) for speech_input in speech_inputs]

									# Test not batched input
									a_     :      Dict 						=     feature_extractor(np_speech_inputs[0]			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0      ).audio_values

									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )

									# Test batched
									a_     :      int 						=     feature_extractor(a_			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0      ).audio_values

									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )

									# Test audio masking
									a_     :      Optional[int] 						=     feature_extractor(
									    a_			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0			,     mask_audio=a_      ).audio_values

									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )

									# Test 2-D numpy arrays are batched.
									a_     :      List[str] 						=     [floats_list((1, x)      )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
									a_     :      Union[str, Any] 						=     np.asarray(a_      )
									a_     :      Dict 						=     feature_extractor(a_			,     return_tensors="np"			,     sampling_rate=4_4_1_0_0      ).audio_values
									self.assertTrue(encoded_audios.ndim == 4      )
									self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size      )
									self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length      )
									self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels      )






							def snake_case_  (   self			,     a_      ):
									a_     :      Optional[int] 						=     load_dataset("hf-internal-testing/librispeech_asr_dummy"			,     "clean"			,     split="validation"      )
									# automatic decoding with librispeech
									a_     :      List[str] 						=     ds.sort("id"      ).select(range(a_      )      )[:num_samples]["audio"]

									return [x["array"] for x in speech_samples]






							def snake_case_  (   self      ):
									a_     :      List[str] 						=     self._load_datasamples(1      )
									a_     :      Any 						=     TvltFeatureExtractor()
									a_     :      Union[str, Any] 						=     feature_extractor(a_			,     return_tensors="pt"      ).audio_values

									self.assertEquals(audio_values.shape			,     (1, 1, 1_9_2, 1_2_8)      )

									a_     :      Dict 						=     torch.tensor([[-0.3_032, -0.2_708], [-0.4_434, -0.4_007]]      )
									self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]			,     a_			,     atol=1e-4      )      )