

'''simple docstring'''


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

import os
from pathlib import Path







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase  )    ->    List[Any]:
	UpperCAmelCase_		:      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]
	UpperCAmelCase_		:      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],
	}
	UpperCAmelCase_		:      Tuple       	=					f"""{src_lang}-{tgt_lang}"""

	UpperCAmelCase_		:      int       	=					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  )
	UpperCAmelCase_		:      str       	=					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
lowerCAmelCase__										= Path(__file__).resolve().parent.parent.parent
lowerCAmelCase__										= 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"]:
						lowerCAmelCase__										= model_cards_dir / "allenai" / model_name
						write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)









'''simple docstring'''


from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
						import tensorflow as tf

						from ..tf_utils import stable_softmax


if is_torch_available():
						import torch


lowerCAmelCase__										= logging.get_logger(__name__)



@add_end_docstrings(
    a_,					r"\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    ",					)
class 					lowercase						(  a_ ):


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								if self.framework == "tf":
									UpperCAmelCase_		:      Dict       	=					tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
								elif self.framework == "pt":
									UpperCAmelCase_		:      Any       	=					torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,			as_tuple=_snake_case)
								else:
									raise ValueError('Unsupported framework')
								return masked_index


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								UpperCAmelCase_		:      Optional[int]       	=					self.get_masked_index(_snake_case)
								UpperCAmelCase_		:      int       	=					np.prod(masked_index.shape)
								if numel < 1:
									raise PipelineException(
									    'fill-mask'    ,			self.model.base_model_prefix    ,			F"""No mask_token ({self.tokenizer.mask_token}) found on the input"""    ,			)


							def 						_snake_case							(			self    ,			_snake_case)							->				int:
								if isinstance(_snake_case    ,			_snake_case):
									for model_input in model_inputs:
										self._ensure_exactly_one_mask_token(model_input['input_ids'][0])
								else:
									for input_ids in model_inputs["input_ids"]:
										self._ensure_exactly_one_mask_token(_snake_case)


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=None    ,			**_snake_case)							->				Dict[str, GenericTensor]:
								if return_tensors is None:
									UpperCAmelCase_		:      Optional[Any]       	=					self.framework
								UpperCAmelCase_		:      str       	=					self.tokenizer(_snake_case    ,			return_tensors=_snake_case)
								self.ensure_exactly_one_mask_token(_snake_case)
								return model_inputs


							def 						_snake_case							(			self    ,			_snake_case)							->				Optional[int]:
								UpperCAmelCase_		:      List[str]       	=					self.model(**_snake_case)
								UpperCAmelCase_		:      Optional[Any]       	=					model_inputs['input_ids']
								return model_outputs


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=5    ,			_snake_case=None)							->				str:
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
									UpperCAmelCase_		:      Optional[int]       	=					target_ids.shape[0]
								UpperCAmelCase_		:      Union[str, Any]       	=					model_outputs['input_ids'][0]
								UpperCAmelCase_		:      Optional[Any]       	=					model_outputs['logits']

								if self.framework == "tf":
									UpperCAmelCase_		:      Optional[int]       	=					tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]

									UpperCAmelCase_		:      Tuple       	=					outputs.numpy()

									UpperCAmelCase_		:      Dict       	=					outputs[0, masked_index, :]
									UpperCAmelCase_		:      List[str]       	=					stable_softmax(_snake_case    ,			axis=-1)
									if target_ids is not None:
										UpperCAmelCase_		:      str       	=					tf.gather_nd(tf.squeeze(_snake_case    ,			0)    ,			target_ids.reshape(-1    ,			1))
										UpperCAmelCase_		:      str       	=					tf.expand_dims(_snake_case    ,			0)

									UpperCAmelCase_		:      int       	=					tf.math.top_k(_snake_case    ,			k=_snake_case)
									UpperCAmelCase_	,    UpperCAmelCase_		:      Dict       	=					topk.values.numpy(), topk.indices.numpy()
								else:
									UpperCAmelCase_		:      List[str]       	=					torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,			as_tuple=_snake_case).squeeze(-1)
									# Fill mask pipeline supports only one ${mask_token} per sample

									UpperCAmelCase_		:      int       	=					outputs[0, masked_index, :]
									UpperCAmelCase_		:      str       	=					logits.softmax(dim=-1)
									if target_ids is not None:
										UpperCAmelCase_		:      List[str]       	=					probs[..., target_ids]

									UpperCAmelCase_	,    UpperCAmelCase_		:      Union[str, Any]       	=					probs.topk(_snake_case)

								UpperCAmelCase_		:      Optional[Any]       	=					[]
								UpperCAmelCase_		:      str       	=					values.shape[0] == 1
								for i, (_values, _predictions) in enumerate(zip(values.tolist()    ,			predictions.tolist())):
									UpperCAmelCase_		:      Union[str, Any]       	=					[]
									for v, p in zip(_values    ,			_predictions):
										# Copy is important since we're going to modify this array in place
										UpperCAmelCase_		:      Union[str, Any]       	=					input_ids.numpy().copy()
										if target_ids is not None:
											UpperCAmelCase_		:      str       	=					target_ids[p].tolist()

										UpperCAmelCase_		:      Union[str, Any]       	=					p
										# Filter padding out:
										UpperCAmelCase_		:      List[str]       	=					tokens[np.where(tokens != self.tokenizer.pad_token_id)]
										# Originally we skip special tokens to give readable output.
										# For multi masks though, the other [MASK] would be removed otherwise
										# making the output look odd, so we add them back
										UpperCAmelCase_		:      Union[str, Any]       	=					self.tokenizer.decode(_snake_case    ,			skip_special_tokens=_snake_case)
										UpperCAmelCase_		:      Tuple       	=					{'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]), 'sequence': sequence}
										row.append(_snake_case)
									result.append(_snake_case)
								if single_mask:
									return result[0]
								return result


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=None)							->				List[str]:
								if isinstance(_snake_case    ,			_snake_case):
									UpperCAmelCase_		:      List[str]       	=					[targets]
								try:
									UpperCAmelCase_		:      Optional[int]       	=					self.tokenizer.get_vocab()
								except Exception:
									UpperCAmelCase_		:      Union[str, Any]       	=					{}
								UpperCAmelCase_		:      List[Any]       	=					[]
								for target in targets:
									UpperCAmelCase_		:      Optional[int]       	=					vocab.get(_snake_case    ,			_snake_case)
									if id_ is None:
										UpperCAmelCase_		:      int       	=					self.tokenizer(
										    _snake_case    ,			add_special_tokens=_snake_case    ,			return_attention_mask=_snake_case    ,			return_token_type_ids=_snake_case    ,			max_length=1    ,			truncation=_snake_case    ,			)['input_ids']
										if len(_snake_case) == 0:
											logger.warning(
											    F"""The specified target token `{target}` does not exist in the model vocabulary. """
											    'We cannot replace it with anything meaningful, ignoring it')
											continue
										UpperCAmelCase_		:      Tuple       	=					input_ids[0]
										# XXX: If users encounter this pass
										# it becomes pretty slow, so let's make sure
										# The warning enables them to fix the input to
										# get faster performance.
										logger.warning(
										    F"""The specified target token `{target}` does not exist in the model vocabulary. """
										    F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.""")
									target_ids.append(id_)
								UpperCAmelCase_		:      Union[str, Any]       	=					list(set(_snake_case))
								if len(_snake_case) == 0:
									raise ValueError('At least one target must be provided when passed.')
								UpperCAmelCase_		:      Dict       	=					np.array(_snake_case)
								return target_ids


							def 						_snake_case							(			self    ,			_snake_case=None    ,			_snake_case=None)							->				Dict:
								UpperCAmelCase_		:      str       	=					{}

								if targets is not None:
									UpperCAmelCase_		:      Dict       	=					self.get_target_ids(_snake_case    ,			_snake_case)
									UpperCAmelCase_		:      Optional[int]       	=					target_ids

								if top_k is not None:
									UpperCAmelCase_		:      List[str]       	=					top_k

								if self.tokenizer.mask_token_id is None:
									raise PipelineException(
									    'fill-mask'    ,			self.model.base_model_prefix    ,			'The tokenizer does not define a `mask_token`.')
								return {}, {}, postprocess_params





							def __call__(			self    ,			_snake_case    ,			*_snake_case    ,			**_snake_case)							->				Optional[int]:
								UpperCAmelCase_		:      Any       	=					super().__call__(_snake_case    ,			**_snake_case)
								if isinstance(_snake_case    ,			_snake_case) and len(_snake_case) == 1:
									return outputs[0]
								return outputs






