






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

import os
from pathlib import Path




def 		__SCREAMING_SNAKE_CASE       (	_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase				):


   """simple docstring"""




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

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

   lowercase_						:     Dict							     =  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				)
   lowercase_						:     int							     =  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
UpperCamelCase__			=      Path(__file__).resolve().parent.parent.parent
UpperCamelCase__			=      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"]:
 UpperCamelCase__			=      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 copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


UpperCamelCase__			=      logging.get_logger(__name__)

UpperCamelCase__			=      {
    'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json',
}


class 							_UpperCAmelCase    (		snake_case      ):
    __lowerCamelCase: Union[str, Any]									=     'deta'
    __lowerCamelCase: str									=     {
        'hidden_size': 'd_model',
        'num_attention_heads': 'encoder_attention_heads',
    }




    def __init__(      self	:							List[str]	,  a	:							Union[str, Any]=None	,  a	:							Dict=9_0_0	,  a	:							str=2_0_4_8	,  a	:							Union[str, Any]=6	,  a	:							int=2_0_4_8	,  a	:							Optional[int]=8	,  a	:							Optional[Any]=6	,  a	:							Optional[Any]=1_0_2_4	,  a	:							Any=8	,  a	:							Dict=0.0	,  a	:							Optional[int]=True	,  a	:							Union[str, Any]="relu"	,  a	:							str=2_5_6	,  a	:							str=0.1	,  a	:							Any=0.0	,  a	:							Optional[Any]=0.0	,  a	:							str=0.02	,  a	:							int=1.0	,  a	:							Tuple=True	,  a	:							Optional[int]=False	,  a	:							str="sine"	,  a	:							List[Any]=5	,  a	:							str=4	,  a	:							Any=4	,  a	:							Optional[Any]=True	,  a	:							Union[str, Any]=3_0_0	,  a	:							List[Any]=True	,  a	:							Tuple=True	,  a	:							Any=1	,  a	:							int=5	,  a	:							Optional[int]=2	,  a	:							Tuple=1	,  a	:							List[str]=1	,  a	:							Tuple=5	,  a	:							Tuple=2	,  a	:							List[str]=0.1	,  a	:							Tuple=0.25	,  **a	:							Optional[int]	,  ):






       '''simple docstring'''






       if backbone_config is None:
          logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."      )
          lowercase_						:     Optional[int]							     =  CONFIG_MAPPING["resnet"](out_features=["stage2", "stage3", "stage4"]      )
       else:
          if isinstance(a	,  a      ):
             lowercase_						:     Any							     =  backbone_config.pop("model_type"      )
             lowercase_						:     str							     =  CONFIG_MAPPING[backbone_model_type]
             lowercase_						:     Any							     =  config_class.from_dict(a      )

       lowercase_						:     Optional[int]							     =  backbone_config
       lowercase_						:     Dict							     =  num_queries
       lowercase_						:     Tuple							     =  max_position_embeddings
       lowercase_						:     Union[str, Any]							     =  d_model
       lowercase_						:     Optional[Any]							     =  encoder_ffn_dim
       lowercase_						:     Any							     =  encoder_layers
       lowercase_						:     int							     =  encoder_attention_heads
       lowercase_						:     Tuple							     =  decoder_ffn_dim
       lowercase_						:     Dict							     =  decoder_layers
       lowercase_						:     Dict							     =  decoder_attention_heads
       lowercase_						:     List[Any]							     =  dropout
       lowercase_						:     Union[str, Any]							     =  attention_dropout
       lowercase_						:     List[str]							     =  activation_dropout
       lowercase_						:     Optional[Any]							     =  activation_function
       lowercase_						:     str							     =  init_std
       lowercase_						:     Dict							     =  init_xavier_std
       lowercase_						:     List[Any]							     =  encoder_layerdrop
       lowercase_						:     Optional[int]							     =  auxiliary_loss
       lowercase_						:     str							     =  position_embedding_type
       # deformable attributes
       lowercase_						:     Optional[int]							     =  num_feature_levels
       lowercase_						:     List[Any]							     =  encoder_n_points
       lowercase_						:     Optional[Any]							     =  decoder_n_points
       lowercase_						:     List[Any]							     =  two_stage
       lowercase_						:     Any							     =  two_stage_num_proposals
       lowercase_						:     List[str]							     =  with_box_refine
       lowercase_						:     Optional[int]							     =  assign_first_stage
       if two_stage is True and with_box_refine is False:
          raise ValueError("If two_stage is True, with_box_refine must be True."      )
       # Hungarian matcher
       lowercase_						:     int							     =  class_cost
       lowercase_						:     Optional[int]							     =  bbox_cost
       lowercase_						:     str							     =  giou_cost
       # Loss coefficients
       lowercase_						:     Optional[int]							     =  mask_loss_coefficient
       lowercase_						:     Union[str, Any]							     =  dice_loss_coefficient
       lowercase_						:     Optional[Any]							     =  bbox_loss_coefficient
       lowercase_						:     Optional[Any]							     =  giou_loss_coefficient
       lowercase_						:     Any							     =  eos_coefficient
       lowercase_						:     str							     =  focal_alpha
       super().__init__(is_encoder_decoder=a	,  **a      )




    @property
    def 					lowerCAmelCase__					(      self	:							Union[str, Any]      ):






       '''simple docstring'''






       return self.encoder_attention_heads




    @property
    def 					lowerCAmelCase__					(      self	:							Union[str, Any]      ):






       '''simple docstring'''






       return self.d_model





    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       lowercase_						:     List[Any]							     =  copy.deepcopy(self.__dict__      )
       lowercase_						:     Union[str, Any]							     =  self.backbone_config.to_dict()
       lowercase_						:     str							     =  self.__class__.model_type
       return output




