





'''simple docstring'''






import argparse
import ast
import logging
import os
import sys

import pandas as pd
import torch
from tqdm import tqdm

from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score  # noqa: E402 # isort:skip


snake_case_     =	logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()
def 							_lowerCamelCase(  UpperCamelCase__    : Optional[int]		)		->  List[Any]:
    if "token" in model_name_or_path:
        return "rag_token"
    if "sequence" in model_name_or_path:
        return "rag_sequence"
    if "bart" in model_name_or_path:
        return "bart"
    return None
def 							_lowerCamelCase(  UpperCamelCase__    : Optional[Any]    ,       UpperCamelCase__    : Optional[int]    ,       UpperCamelCase__    : Dict		)		->  List[Any]:
    return max(metric_fn(UpperCamelCase__    ,       UpperCamelCase__		) for gt in ground_truths		)
def 							_lowerCamelCase(  UpperCamelCase__    : List[str]    ,       UpperCamelCase__    : str    ,       UpperCamelCase__    : Tuple		)		->  List[Any]:
    A       :       Optional[int]							=						[line.strip() for line in open(UpperCamelCase__    ,       '''r'''		).readlines()]
    A       :       Tuple							=						[]

    if args.gold_data_mode == "qa":
        A       :       Tuple							=						pd.read_csv(UpperCamelCase__    ,       sep='''\t'''    ,       header=UpperCamelCase__		)
        for answer_list in data[1]:
            A       :       Union[str, Any]							=						ast.literal_eval(UpperCamelCase__		)
            answers.append(UpperCamelCase__		)
    else:
        A       :       Union[str, Any]							=						[line.strip() for line in open(UpperCamelCase__    ,       '''r'''		).readlines()]
        A       :       Union[str, Any]							=						[[reference] for reference in references]

    A       :       Any							=						0
    for prediction, ground_truths in zip(UpperCamelCase__    ,       UpperCamelCase__		):
        total += 1
        em += metric_max_over_ground_truths(UpperCamelCase__    ,       UpperCamelCase__    ,       UpperCamelCase__		)
        fa += metric_max_over_ground_truths(UpperCamelCase__    ,       UpperCamelCase__    ,       UpperCamelCase__		)

    A       :       Tuple							=						1_0_0.0 * em / total
    A       :       int							=						1_0_0.0 * fa / total

    logger.info(F'''F1: {fa:.2f}'''		)
    logger.info(F'''EM: {em:.2f}'''		)
def 							_lowerCamelCase(  UpperCamelCase__    : Tuple    ,       UpperCamelCase__    : Union[str, Any]    ,       UpperCamelCase__    : int		)		->  Optional[Any]:
    A       :       Optional[Any]							=						args.k
    A       :       List[str]							=						[line.strip() for line in open(UpperCamelCase__    ,       '''r'''		).readlines()]
    A       :       Optional[Any]							=						[line.strip() for line in open(UpperCamelCase__    ,       '''r'''		).readlines()]

    A       :       Any							=						0
    for hypo, reference in zip(UpperCamelCase__    ,       UpperCamelCase__		):
        A       :       Tuple							=						set(hypo.split('''\t'''		)[:k]		)
        A       :       Optional[Any]							=						set(reference.split('''\t'''		)		)
        total += 1
        em += len(hypo_provenance & ref_provenance		) / k

    A       :       List[str]							=						1_0_0.0 * em / total
    logger.info(F'''Precision@{k}: {em: .2f}'''		)
def 							_lowerCamelCase(  UpperCamelCase__    : Optional[int]    ,       UpperCamelCase__    : str    ,       UpperCamelCase__    : Optional[int]		)		->  List[str]:
    def strip_title(UpperCamelCase__    : Optional[int]		):
        if title.startswith('''"'''		):
            A       :       List[str]							=						title[1:]
        if title.endswith('''"'''		):
            A       :       Tuple							=						title[:-1]
        return title

    A       :       List[Any]							=						rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
        UpperCamelCase__    ,       return_tensors='''pt'''    ,       padding=UpperCamelCase__    ,       truncation=UpperCamelCase__    ,       )['''input_ids'''].to(args.device		)

    A       :       List[Any]							=						rag_model.rag.question_encoder(UpperCamelCase__		)
    A       :       List[str]							=						question_enc_outputs[0]

    A       :       Tuple							=						rag_model.retriever(
        UpperCamelCase__    ,       question_enc_pool_output.cpu().detach().to(torch.floataa		).numpy()    ,       prefix=rag_model.rag.generator.config.prefix    ,       n_docs=rag_model.config.n_docs    ,       return_tensors='''pt'''    ,       )
    A       :       List[Any]							=						rag_model.retriever.index.get_doc_dicts(result.doc_ids		)
    A       :       List[str]							=						[]
    for docs in all_docs:
        A       :       Any							=						[strip_title(UpperCamelCase__		) for title in docs['''title''']]
        provenance_strings.append('''\t'''.join(UpperCamelCase__		)		)
    return provenance_strings
def 							_lowerCamelCase(  UpperCamelCase__    : Optional[int]    ,       UpperCamelCase__    : Union[str, Any]    ,       UpperCamelCase__    : str		)		->  List[str]:
    with torch.no_grad():
        A       :       Optional[int]							=						rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
            UpperCamelCase__    ,       return_tensors='''pt'''    ,       padding=UpperCamelCase__    ,       truncation=UpperCamelCase__		)

        A       :       Dict							=						inputs_dict.input_ids.to(args.device		)
        A       :       Optional[Any]							=						inputs_dict.attention_mask.to(args.device		)
        A       :       str							=						rag_model.generate(  # rag_model overwrites generate
            UpperCamelCase__    ,       attention_mask=UpperCamelCase__    ,       num_beams=args.num_beams    ,       min_length=args.min_length    ,       max_length=args.max_length    ,       early_stopping=UpperCamelCase__    ,       num_return_sequences=1    ,       bad_words_ids=[[0, 0]]    ,       )
        A       :       Dict							=						rag_model.retriever.generator_tokenizer.batch_decode(UpperCamelCase__    ,       skip_special_tokens=UpperCamelCase__		)

        if args.print_predictions:
            for q, a in zip(UpperCamelCase__    ,       UpperCamelCase__		):
                logger.info('''Q: {} - A: {}'''.format(UpperCamelCase__    ,       UpperCamelCase__		)		)

        return answers
def 							_lowerCamelCase(  )		->  Optional[int]:
    A       :       Optional[Any]							=						argparse.ArgumentParser()
    parser.add_argument(
        '''--model_type'''    ,       choices=['''rag_sequence''', '''rag_token''', '''bart''']    ,       type=UpperCamelCase__    ,       help=(
            '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the'''
            ''' model_name_or_path'''
        )    ,       )
    parser.add_argument(
        '''--index_name'''    ,       default=UpperCamelCase__    ,       choices=['''exact''', '''compressed''', '''legacy''']    ,       type=UpperCamelCase__    ,       help='''RAG model retriever type'''    ,       )
    parser.add_argument(
        '''--index_path'''    ,       default=UpperCamelCase__    ,       type=UpperCamelCase__    ,       help='''Path to the retrieval index'''    ,       )
    parser.add_argument('''--n_docs'''    ,       default=5    ,       type=UpperCamelCase__    ,       help='''Number of retrieved docs'''		)
    parser.add_argument(
        '''--model_name_or_path'''    ,       default=UpperCamelCase__    ,       type=UpperCamelCase__    ,       required=UpperCamelCase__    ,       help='''Path to pretrained checkpoints or model identifier from huggingface.co/models'''    ,       )
    parser.add_argument(
        '''--eval_mode'''    ,       choices=['''e2e''', '''retrieval''']    ,       default='''e2e'''    ,       type=UpperCamelCase__    ,       help=(
            '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates'''
            ''' precision@k.'''
        )    ,       )
    parser.add_argument('''--k'''    ,       default=1    ,       type=UpperCamelCase__    ,       help='''k for the precision@k calculation'''		)
    parser.add_argument(
        '''--evaluation_set'''    ,       default=UpperCamelCase__    ,       type=UpperCamelCase__    ,       required=UpperCamelCase__    ,       help='''Path to a file containing evaluation samples'''    ,       )
    parser.add_argument(
        '''--gold_data_path'''    ,       default=UpperCamelCase__    ,       type=UpperCamelCase__    ,       required=UpperCamelCase__    ,       help='''Path to a tab-separated file with gold samples'''    ,       )
    parser.add_argument(
        '''--gold_data_mode'''    ,       default='''qa'''    ,       type=UpperCamelCase__    ,       choices=['''qa''', '''ans''']    ,       help=(
            '''Format of the gold data file'''
            '''qa - a single line in the following format: question [tab] answer_list'''
            '''ans - a single line of the gold file contains the expected answer string'''
        )    ,       )
    parser.add_argument(
        '''--predictions_path'''    ,       type=UpperCamelCase__    ,       default='''predictions.txt'''    ,       help='''Name of the predictions file, to be stored in the checkpoints directory'''    ,       )
    parser.add_argument(
        '''--eval_all_checkpoints'''    ,       action='''store_true'''    ,       help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number'''    ,       )
    parser.add_argument(
        '''--eval_batch_size'''    ,       default=8    ,       type=UpperCamelCase__    ,       help='''Batch size per GPU/CPU for evaluation.'''    ,       )
    parser.add_argument(
        '''--recalculate'''    ,       help='''Recalculate predictions even if the prediction file exists'''    ,       action='''store_true'''    ,       )
    parser.add_argument(
        '''--num_beams'''    ,       default=4    ,       type=UpperCamelCase__    ,       help='''Number of beams to be used when generating answers'''    ,       )
    parser.add_argument('''--min_length'''    ,       default=1    ,       type=UpperCamelCase__    ,       help='''Min length of the generated answers'''		)
    parser.add_argument('''--max_length'''    ,       default=50    ,       type=UpperCamelCase__    ,       help='''Max length of the generated answers'''		)

    parser.add_argument(
        '''--print_predictions'''    ,       action='''store_true'''    ,       help='''If True, prints predictions while evaluating.'''    ,       )
    parser.add_argument(
        '''--print_docs'''    ,       action='''store_true'''    ,       help='''If True, prints docs retried while generating.'''    ,       )
    A       :       int							=						parser.parse_args()
    A       :       Optional[Any]							=						torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''		)
    return args
def 							_lowerCamelCase(  UpperCamelCase__    : List[str]		)		->  int:
    A       :       Tuple							=						{}
    if args.model_type is None:
        A       :       Tuple							=						infer_model_type(args.model_name_or_path		)
        assert args.model_type is not None
    if args.model_type.startswith('''rag'''		):
        A       :       List[str]							=						RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration
        A       :       Optional[Any]							=						args.n_docs
        if args.index_name is not None:
            A       :       Optional[Any]							=						args.index_name
        if args.index_path is not None:
            A       :       Any							=						args.index_path
    else:
        A       :       Union[str, Any]							=						BartForConditionalGeneration

    A       :       Optional[int]							=						(
        [f.path for f in os.scandir(args.model_name_or_path		) if f.is_dir()]
        if args.eval_all_checkpoints
        else [args.model_name_or_path]
    )

    logger.info('''Evaluate the following checkpoints: %s'''    ,       UpperCamelCase__		)

    A       :       Dict							=						get_scores if args.eval_mode == '''e2e''' else get_precision_at_k
    A       :       Union[str, Any]							=						evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval

    for checkpoint in checkpoints:
        if os.path.exists(args.predictions_path		) and (not args.recalculate):
            logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path		)		)
            score_fn(UpperCamelCase__    ,       args.predictions_path    ,       args.gold_data_path		)
            continue

        logger.info('''***** Running evaluation for {} *****'''.format(UpperCamelCase__		)		)
        logger.info('''  Batch size = %d'''    ,       args.eval_batch_size		)
        logger.info('''  Predictions will be stored under {}'''.format(args.predictions_path		)		)

        if args.model_type.startswith('''rag'''		):
            A       :       Optional[int]							=						RagRetriever.from_pretrained(UpperCamelCase__    ,       **UpperCamelCase__		)
            A       :       Any							=						model_class.from_pretrained(UpperCamelCase__    ,       retriever=UpperCamelCase__    ,       **UpperCamelCase__		)
            model.retriever.init_retrieval()
        else:
            A       :       str							=						model_class.from_pretrained(UpperCamelCase__    ,       **UpperCamelCase__		)
        model.to(args.device		)

        with open(args.evaluation_set    ,       '''r'''		) as eval_file, open(args.predictions_path    ,       '''w'''		) as preds_file:
            A       :       Optional[Any]							=						[]
            for line in tqdm(UpperCamelCase__		):
                questions.append(line.strip()		)
                if len(UpperCamelCase__		) == args.eval_batch_size:
                    A       :       Union[str, Any]							=						evaluate_batch_fn(UpperCamelCase__    ,       UpperCamelCase__    ,       UpperCamelCase__		)
                    preds_file.write('''\n'''.join(UpperCamelCase__		) + '''\n'''		)
                    preds_file.flush()
                    A       :       int							=						[]
            if len(UpperCamelCase__		) > 0:
                A       :       List[str]							=						evaluate_batch_fn(UpperCamelCase__    ,       UpperCamelCase__    ,       UpperCamelCase__		)
                preds_file.write('''\n'''.join(UpperCamelCase__		)		)
                preds_file.flush()

            score_fn(UpperCamelCase__    ,       args.predictions_path    ,       args.gold_data_path		)


if __name__ == "__main__":
     snake_case_     =	get_args()
     main(args)







'''simple docstring'''






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

import os
from pathlib import Path
def 							_lowerCamelCase(  UpperCamelCase__    : List[Any]    ,       UpperCamelCase__    : Optional[Any]    ,       UpperCamelCase__    : List[Any]		)		->  List[Any]:
    A       :       Any							=						{
        '''en''': '''Machine learning is great, isn\'t it?''',
        '''ru''': '''Машинное обучение - это здорово, не так ли?''',
        '''de''': '''Maschinelles Lernen ist großartig, oder?''',
    }

    # BLUE scores as follows:
    # "pair": [fairseq, transformers]
    A       :       List[Any]							=						{
        '''ru-en''': ['''[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)''', '''39.20'''],
        '''en-ru''': ['''[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)''', '''33.47'''],
        '''en-de''': ['''[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)''', '''42.83'''],
        '''de-en''': ['''[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)''', '''41.35'''],
    }
    A       :       List[Any]							=						F'''{src_lang}-{tgt_lang}'''

    A       :       Any							=						F'''
---
language: 
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt19
- facebook
license: apache-2.0
datasets:
- wmt19
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.

For more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).

The abbreviation FSMT stands for FairSeqMachineTranslation

All four models are available:

* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)
* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)
* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)
* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)

## Intended uses & limitations

#### How to use

```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = "facebook/wmt19-{src_lang}-{tgt_lang}"
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

- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)

## Training data

Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).

## Eval results

pair   | fairseq | transformers
-------|---------|----------
{pair}  | {scores[pair][0]} | {scores[pair][1]}

The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:
- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).
- re-ranking

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=15
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 facebook/wmt19-$PAIR $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
```
note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.

## 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

```bibtex
@inproceedings{{...,
  year={{2020}},
  title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},
  author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},
  booktitle={{Proc. of WMT}},
}}
```


## TODO

- port model ensemble (fairseq uses 4 model checkpoints)

'''
    os.makedirs(UpperCamelCase__    ,       exist_ok=UpperCamelCase__		)
    A       :       Optional[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
snake_case_     =	Path(__file__).resolve().parent.parent.parent
snake_case_     =	repo_dir / """model_cards"""

for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
     snake_case_ ,  snake_case_ ,  snake_case_     =	model_name.split("""-""")
     snake_case_     =	model_cards_dir / """facebook""" / model_name
     write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
