



"""simple docstring"""






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

import os
from pathlib import Path






def 	snake_case__  (						__lowerCamelCase							:       Tuple				,						__lowerCamelCase							:       Dict				,						__lowerCamelCase							:       Dict				,						__lowerCamelCase							:       Any      ):
			"""simple docstring"""
			lowerCamelCase__						:						str						      ={
			    '''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__						:						List[Any]						      ={
			    '''wmt19-de-en-6-6-base''': [0, 38.37],
			    '''wmt19-de-en-6-6-big''': [0, 39.90],
			}
			lowerCamelCase__						:						Any						      =f'''{src_lang}-{tgt_lang}'''

			lowerCamelCase__						:						Tuple						      =f'''
---

language:
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt19
- allenai
license: apache-2.0
datasets:
- wmt19
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of fairseq-based [wmt19 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).

2 models are available:

* [wmt19-de-en-6-6-big](https://huggingface.co/allenai/wmt19-de-en-6-6-big)
* [wmt19-de-en-6-6-base](https://huggingface.co/allenai/wmt19-de-en-6-6-base)


## 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   |  transformers
-------|---------
{model_name}  |  {scores[model_name][1]}

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 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 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/wmt19/)
- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)


### 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=__lowerCamelCase				,						exist_ok=__lowerCamelCase      )
			lowerCamelCase__						:						Optional[int]						      =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
_lowercase					:					Optional[Any] 		=		Path(__file__).resolve().parent.parent.parent
_lowercase					:					str 		=		repo_dir / "model_cards"

for model_name in ["wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big"]:
		_lowercase					:					Any 		=		model_cards_dir / "allenai" / model_name
		write_model_card(model_card_dir, src_lang="de", tgt_lang="en", model_name=model_name)






import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


UpperCAmelCase__						:	Any	     = logging.get_logger(__name__)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				List[str]	):

      """simple docstring"""
      super().__init__()
      if version.parse(torch.__version__	) < version.parse('''1.12.0'''	):
         raise ImportError(
             F"""You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use """
             '''PytorchGELUTanh. Please upgrade torch.'''	)


   def 					__magic_name__							(   self	:				Any     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return nn.functional.gelu(lowerCAmelCase_     ,     approximate='''tanh'''	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Tuple     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi	) * (input + 0.044715 * torch.pow(lowerCAmelCase_     ,     3.0	))	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				Tuple     ,     lowerCAmelCase_	:				bool = False	):

      """simple docstring"""
      super().__init__()
      if use_gelu_python:
         _A:    Union[str, Any]						     =			self._gelu_python
      else:
         _A:    Union[str, Any]						     =			nn.functional.gelu


   def 					__magic_name__							(   self	:				Union[str, Any]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0	)	))


   def 					__magic_name__							(   self	:				Any     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return self.act(lowerCAmelCase_	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Optional[int]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input)	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Optional[int]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input * torch.sigmoid(1.702 * input	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				str     ,     lowerCAmelCase_	:				float     ,     lowerCAmelCase_	:				float	):

      """simple docstring"""
      if min > max:
         raise ValueError(F"""min should be < max (got min: {min}, max: {max})"""	)

      super().__init__()
      _A:    Tuple						     =			min
      _A:    str						     =			max


   def 					__magic_name__							(   self	:				int     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return torch.clip(gelu(lowerCAmelCase_	)     ,     self.min     ,     self.max	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				Optional[Any]	):

      """simple docstring"""
      super().__init__()
      _A:    Any						     =			math.sqrt(2 / math.pi	)


   def 					__magic_name__							(   self	:				Union[str, Any]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(lowerCAmelCase_     ,     3	))	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				str     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return nn.functional.silu(lowerCAmelCase_	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				Union[str, Any]	):

      """simple docstring"""
      super().__init__()
      if version.parse(torch.__version__	) < version.parse('''1.9.0'''	):
         _A:    Optional[Any]						     =			self._mish_python
      else:
         _A:    int						     =			nn.functional.mish


   def 					__magic_name__							(   self	:				Optional[int]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input * torch.tanh(nn.functional.softplus(lowerCAmelCase_	)	)


   def 					__magic_name__							(   self	:				Any     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return self.act(lowerCAmelCase_	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Tuple     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Dict     ,     lowerCAmelCase_	:				List[str]     ,     lowerCAmelCase_	:				Tuple=0.707107     ,     lowerCAmelCase_	:				Union[str, Any]=0.282095	):

      """simple docstring"""
      _A:    Any						     =			(input - mu).div(sigma * math.sqrt(2.0	)	)
      return 0.5 * (1.0 + torch.erf(lowerCAmelCase_	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Union[str, Any]     ,     lowerCAmelCase_	:				List[Any]	):

      """simple docstring"""
      _A:    Optional[int]						     =			nn.functional.relu(lowerCAmelCase_	)
      _A:    Any						     =			torch.square(lowerCAmelCase_	)
      return squared






class UpperCAmelCase  (		SCREAMING_SNAKE_CASE__  ):





   '''simple docstring'''


   def __getitem__(   self	:				List[Any]     ,     lowerCAmelCase_	:				Tuple	):

      """simple docstring"""
      _A:    Any						     =			super().__getitem__(lowerCAmelCase_	)
      _A     ,    _A:    List[str]						     =			content if isinstance(lowerCAmelCase_     ,     lowerCAmelCase_	) else (content, {})
      return cls(**lowerCAmelCase_	)

UpperCAmelCase__						:	List[str]	     = {
    'gelu': GELUActivation,
    'gelu_10': (ClippedGELUActivation, {'min': -10, 'max': 10}),
    'gelu_fast': FastGELUActivation,
    'gelu_new': NewGELUActivation,
    'gelu_python': (GELUActivation, {'use_gelu_python': True}),
    'gelu_pytorch_tanh': PytorchGELUTanh,
    'gelu_accurate': AccurateGELUActivation,
    'laplace': LaplaceActivation,
    'linear': LinearActivation,
    'mish': MishActivation,
    'quick_gelu': QuickGELUActivation,
    'relu': nn.ReLU,
    'relu2': ReLUSquaredActivation,
    'relu6': nn.ReLUa,
    'sigmoid': nn.Sigmoid,
    'silu': SiLUActivation,
    'swish': SiLUActivation,
    'tanh': nn.Tanh,
}
UpperCAmelCase__						:	List[str]	     = ClassInstantier(ACTaCLS)






def     lowerCamelCase__				(   a ) ->  List[str]:
   if activation_string in ACTaFN:
      return ACTaFN[activation_string]
   else:
      raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )


# For backwards compatibility with: from activations import gelu_python
UpperCAmelCase__						:	Any	     = get_activation('gelu_python')
UpperCAmelCase__						:	Dict	     = get_activation('gelu_new')
UpperCAmelCase__						:	List[Any]	     = get_activation('gelu')
UpperCAmelCase__						:	Dict	     = get_activation('gelu_fast')
UpperCAmelCase__						:	str	     = get_activation('quick_gelu')
UpperCAmelCase__						:	Union[str, Any]	     = get_activation('silu')
UpperCAmelCase__						:	List[Any]	     = get_activation('mish')





UpperCAmelCase__						:	int	     = get_activation('linear')



