





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

import os
from pathlib import Path


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		int     ,							__lowercase:		Union[str, Any]     ,							__lowercase:		Tuple     ,							__lowercase:		Optional[int]):



  '''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			=				{
      '''wmt19-de-en-6-6-base''': [0, 38.37],
      '''wmt19-de-en-6-6-big''': [0, 39.90],
  }
  __lowerCAmelCase			=				F'''{src_lang}-{tgt_lang}'''

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


# make sure we are under the root of the project
__lowercase													=			Path(__file__).resolve().parent.parent.parent
__lowercase													=			repo_dir / """model_cards"""

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







import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand

class   __snake_case				(			_a   ):






    '''simple docstring'''





    @staticmethod
    def 	A		(   snake_case						:		ArgumentParser							):

      """simple docstring"""





      __lowerCAmelCase			=				parser.add_parser('''login'''			,						help='''Log in using the same credentials as on huggingface.co'''							)
      login_parser.set_defaults(func=lambda snake_case							: LoginCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''whoami'''			,						help='''Find out which huggingface.co account you are logged in as.'''							)
      whoami_parser.set_defaults(func=lambda snake_case							: WhoamiCommand(snake_case							)							)
      __lowerCAmelCase			=				parser.add_parser('''logout'''			,						help='''Log out'''							)
      logout_parser.set_defaults(func=lambda snake_case							: LogoutCommand(snake_case							)							)

      # new system: git-based repo system
      __lowerCAmelCase			=				parser.add_parser(
          '''repo'''			,						help='''Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.'''			,						)
      __lowerCAmelCase			=				repo_parser.add_subparsers(
          help='''Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands'''							)
      __lowerCAmelCase			=				repo_subparsers.add_parser(
          '''create'''			,						help='''Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co'''							)
      repo_create_parser.add_argument(
          '''name'''			,						type=snake_case			,						help='''Name for your model\'s repo. Will be namespaced under your username to build the model id.'''			,						)
      repo_create_parser.add_argument('''--organization'''			,						type=snake_case			,						help='''Optional: organization namespace.'''							)
      repo_create_parser.add_argument('''-y'''			,						'''--yes'''			,						action='''store_true'''			,						help='''Optional: answer Yes to the prompt'''							)
      repo_create_parser.set_defaults(func=lambda snake_case							: RepoCreateCommand(snake_case							)							)


class   __snake_case				:






    '''simple docstring'''
    _lowerCAmelCase     =	"""\u001b[1m"""
    _lowerCAmelCase     =	"""\u001b[31m"""
    _lowerCAmelCase     =	"""\u001b[90m"""
    _lowerCAmelCase     =	"""\u001b[0m"""





    @classmethod
    def 	A		(   cls						:		str			,						snake_case						:		Optional[int]							):

      """simple docstring"""





      return f'''{cls._bold}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Optional[Any]			,						snake_case						:		str							):

      """simple docstring"""





      return f'''{cls._bold}{cls._red}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Dict			,						snake_case						:		List[Any]							):

      """simple docstring"""





      return f'''{cls._gray}{s}{cls._reset}'''


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		List[List[Union[str, int]]]     ,							__lowercase:		List[str]):



  '''simple docstring'''






  __lowerCAmelCase			=				[max(len(str(__lowercase)) for x in col) for col in zip(*__lowercase     ,							__lowercase)]
  __lowerCAmelCase			=				('''{{:{}}} ''' * len(__lowercase)).format(*__lowercase)
  __lowerCAmelCase			=				[]
  lines.append(row_format.format(*__lowercase))
  lines.append(row_format.format(*['''-''' * w for w in col_widths]))
  for row in rows:
    lines.append(row_format.format(*__lowercase))
  return "\n".join(__lowercase)

class   __snake_case				:






    '''simple docstring'''





    def __init__(   self						:		List[str]			,						snake_case						:		List[str]							):

      """simple docstring"""





      __lowerCAmelCase			=				args


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		List[Any]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `huggingface-cli login` uses an outdated login mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli login instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		int							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use '''
              '''`huggingface-cli whoami` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit()
      try:
        __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
        print(snake_case							)
        if orgs:
          print(ANSI.bold('''orgs: '''							)			,						''','''.join(snake_case							)							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Any							):

      """simple docstring"""





      print(
          ANSI.red(
              '''ERROR! `transformers-cli logout` uses an outdated logout mechanism '''
              '''that is not compatible with the Hugging Face Hub backend anymore. '''
              '''Please use `huggingface-cli logout instead.'''							)							)


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Optional[int]							):

      """simple docstring"""





      print(
          ANSI.red(
              '''WARNING! Managing repositories through transformers-cli is deprecated. '''
              '''Please use `huggingface-cli` instead.'''							)							)
      __lowerCAmelCase			=				HfFolder.get_token()
      if token is None:
        print('''Not logged in'''							)
        exit(1							)
      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print('''Looks like you do not have git installed, please install.'''							)

      try:
        __lowerCAmelCase			=				subprocess.check_output(['''git-lfs''', '''--version''']							).decode('''utf-8'''							)
        print(ANSI.gray(stdout.strip()							)							)
      except FileNotFoundError:
        print(
            ANSI.red(
                '''Looks like you do not have git-lfs installed, please install.'''
                ''' You can install from https://git-lfs.github.com/.'''
                ''' Then run `git lfs install` (you only have to do this once).'''							)							)
      print(''''''							)

      __lowerCAmelCase	,						__lowerCAmelCase			=				whoami(snake_case							)
      __lowerCAmelCase			=				self.args.organization if self.args.organization is not None else user
      __lowerCAmelCase			=				f'''{namespace}/{self.args.name}'''
      print(f'''You are about to create {ANSI.bold(snake_case							)}'''							)

      if not self.args.yes:
        __lowerCAmelCase			=				input('''Proceed? [Y/n] '''							).lower()
        if not (choice == "" or choice == "y" or choice == "yes"):
          print('''Abort'''							)
          exit()
      try:
        __lowerCAmelCase			=				create_repo(snake_case			,						name=self.args.name			,						organization=self.args.organization							)
      except HTTPError as e:
        print(snake_case							)
        print(ANSI.red(e.response.text							)							)
        exit(1							)
      print('''\nYour repo now lives at:'''							)
      print(f'''  {ANSI.bold(snake_case							)}'''							)
      print('''\nYou can clone it locally with the command below, and commit/push as usual.'''							)
      print(f'''\n  git clone {url}'''							)
      print(''''''							)
