




import warnings
from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__A								=       logging.get_logger(__name__)







class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			snake_case_  						=			['''input_ids''', '''attention_mask''']


			def __init__( self     ,		lowerCamelCase__="</s>"     ,		lowerCamelCase__="<unk>"     ,		lowerCamelCase__="<pad>"     ,		lowerCamelCase__=125     ,		lowerCamelCase__=None     ,		**lowerCamelCase__     ,		)       -> None:



							'''simple docstring'''
							# Add extra_ids to the special token list
							if extra_ids > 0 and additional_special_tokens is None:
											__lowerCamelCase									=       [f"""<extra_id_{i}>""" for i in range(lowerCamelCase__				)]
							elif extra_ids > 0 and additional_special_tokens is not None:
											# Check that we have the right number of extra_id special tokens
											__lowerCamelCase									=       len(set(filter(lambda lowerCamelCase__				: bool('extra_id' in str(lowerCamelCase__				)				)     ,		lowerCamelCase__				)				)				)
											if extra_tokens != extra_ids:
															raise ValueError(
															    f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"""
															    ' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the'
															    ' extra_ids tokens'				)

							__lowerCamelCase									=       AddedToken(lowerCamelCase__     ,		lstrip=lowerCamelCase__     ,		rstrip=lowerCamelCase__				) if isinstance(lowerCamelCase__     ,		lowerCamelCase__				) else pad_token
							__lowerCamelCase									=       AddedToken(lowerCamelCase__     ,		lstrip=lowerCamelCase__     ,		rstrip=lowerCamelCase__				) if isinstance(lowerCamelCase__     ,		lowerCamelCase__				) else eos_token
							__lowerCamelCase									=       AddedToken(lowerCamelCase__     ,		lstrip=lowerCamelCase__     ,		rstrip=lowerCamelCase__				) if isinstance(lowerCamelCase__     ,		lowerCamelCase__				) else unk_token

							super().__init__(
							    eos_token=lowerCamelCase__     ,		unk_token=lowerCamelCase__     ,		pad_token=lowerCamelCase__     ,		extra_ids=lowerCamelCase__     ,		additional_special_tokens=lowerCamelCase__     ,		**lowerCamelCase__     ,		)

							__lowerCamelCase									=       extra_ids

							__lowerCamelCase									=       2**8  # utf is 8 bits

							# define special tokens dict
							__lowerCamelCase									=       {
							    self.pad_token: 0,
							    self.eos_token: 1,
							    self.unk_token: 2,
							}
							__lowerCamelCase									=       len(self.special_tokens_encoder				)
							__lowerCamelCase									=       len(lowerCamelCase__				)
							for i, token in enumerate(lowerCamelCase__				):
											__lowerCamelCase									=       self.vocab_size + i - n
							__lowerCamelCase									=       {v: k for k, v in self.special_tokens_encoder.items()}


			@property
			def  lowercase_       ( self				)       -> int:



							'''simple docstring'''
							return self._utf_vocab_size + self._num_special_tokens + self._extra_ids


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = False				)       -> List[int]:



							'''simple docstring'''
							if already_has_special_tokens:
											return super().get_special_tokens_mask(
											    token_ids_a=lowerCamelCase__     ,		token_ids_a=lowerCamelCase__     ,		already_has_special_tokens=lowerCamelCase__				)

							# normal case: some special tokens
							if token_ids_a is None:
											return ([0] * len(lowerCamelCase__				)) + [1]
							return ([0] * len(lowerCamelCase__				)) + [1] + ([0] * len(lowerCamelCase__				)) + [1]


			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> List[int]:



							'''simple docstring'''
							if len(lowerCamelCase__				) > 0 and token_ids[-1] == self.eos_token_id:
											warnings.warn(
											    f"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"""
											    ' eos tokens being added.'				)
											return token_ids
							else:
											return token_ids + [self.eos_token_id]


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = None				)       -> List[int]:



							'''simple docstring'''
							__lowerCamelCase									=       [self.eos_token_id]

							if token_ids_a is None:
											return len(token_ids_a + eos				) * [0]
							return len(token_ids_a + eos + token_ids_a + eos				) * [0]


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = None				)       -> List[int]:



							'''simple docstring'''
							__lowerCamelCase									=       self._add_eos_if_not_present(lowerCamelCase__				)
							if token_ids_a is None:
											return token_ids_a
							else:
											__lowerCamelCase									=       self._add_eos_if_not_present(lowerCamelCase__				)
											return token_ids_a + token_ids_a


			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> List[str]:



							'''simple docstring'''
							__lowerCamelCase									=       [chr(lowerCamelCase__				) for i in text.encode('utf-8'				)]
							return tokens


			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Dict:



							'''simple docstring'''
							if token in self.special_tokens_encoder:
											__lowerCamelCase									=       self.special_tokens_encoder[token]
							elif token in self.added_tokens_encoder:
											__lowerCamelCase									=       self.added_tokens_encoder[token]
							elif len(lowerCamelCase__				) != 1:
											__lowerCamelCase									=       self.unk_token_id
							else:
											__lowerCamelCase									=       ord(lowerCamelCase__				) + self._num_special_tokens
							return token_id


			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Any:



							'''simple docstring'''
							if index in self.special_tokens_decoder:
											__lowerCamelCase									=       self.special_tokens_decoder[index]
							else:
											__lowerCamelCase									=       chr(index - self._num_special_tokens				)
							return token


			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> int:



							'''simple docstring'''
							__lowerCamelCase									=       b''
							for token in tokens:
											if token in self.special_tokens_decoder:
															__lowerCamelCase									=       self.special_tokens_decoder[token].encode('utf-8'				)
											elif token in self.added_tokens_decoder:
															__lowerCamelCase									=       self.special_tokens_decoder[token].encode('utf-8'				)
											elif token in self.special_tokens_encoder:
															__lowerCamelCase									=       token.encode('utf-8'				)
											elif token in self.added_tokens_encoder:
															__lowerCamelCase									=       token.encode('utf-8'				)
											else:
															__lowerCamelCase									=       bytes([ord(lowerCamelCase__				)]				)
											bstring += tok_string
							__lowerCamelCase									=       bstring.decode('utf-8'     ,		errors='ignore'				)
							return string






			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = None				)       -> Tuple[str]:



							'''simple docstring'''
							return ()








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

import os
from pathlib import Path







def      lowerCamelCase_						(			UpperCamelCase__							: int					,	UpperCamelCase__							: Optional[int]					,	UpperCamelCase__							: int					,	UpperCamelCase__							: str )	->			List[str]:





				"""simple docstring"""


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

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

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


# make sure we are under the root of the project
__A								=       Path(__file__).resolve().parent.parent.parent
__A								=       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"]:
					__A								=       model_cards_dir / "allenai" / model_name
					write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)


