





'''simple docstring'''






import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel


class   _lowercase						:


   def __init__( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase=13    ,   _UpperCAmelCase=7    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=False    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=99    ,   _UpperCAmelCase=32    ,   _UpperCAmelCase=5    ,   _UpperCAmelCase=4    ,   _UpperCAmelCase=37    ,   _UpperCAmelCase="gelu"    ,   _UpperCAmelCase=0.1    ,   _UpperCAmelCase=0.1    ,   _UpperCAmelCase=512    ,   _UpperCAmelCase=16    ,   _UpperCAmelCase=2    ,   _UpperCAmelCase=0.02    ,   _UpperCAmelCase=3    ,   _UpperCAmelCase=4    ,   _UpperCAmelCase=None    ,   ):
       A       :       str							=						parent
       A       :       Union[str, Any]							=						batch_size
       A       :       Tuple							=						seq_length
       A       :       Optional[Any]							=						is_training
       A       :       List[Any]							=						use_input_mask
       A       :       int							=						use_token_type_ids
       A       :       Optional[Any]							=						use_labels
       A       :       Optional[int]							=						vocab_size
       A       :       Tuple							=						hidden_size
       A       :       Dict							=						num_hidden_layers
       A       :       Optional[Any]							=						num_attention_heads
       A       :       Union[str, Any]							=						intermediate_size
       A       :       Tuple							=						hidden_act
       A       :       List[str]							=						hidden_dropout_prob
       A       :       Dict							=						attention_probs_dropout_prob
       A       :       List[Any]							=						max_position_embeddings
       A       :       Any							=						type_vocab_size
       A       :       int							=						type_sequence_label_size
       A       :       Dict							=						initializer_range
       A       :       Optional[Any]							=						num_labels
       A       :       List[str]							=						num_choices
       A       :       List[Any]							=						scope


   def 					snake_case				( self					):
       A       :       Any							=						ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size					)

       A       :       Union[str, Any]							=						None
       if self.use_input_mask:
           A       :       int							=						random_attention_mask([self.batch_size, self.seq_length]					)

       A       :       Union[str, Any]							=						None
       if self.use_token_type_ids:
           A       :       Dict							=						ids_tensor([self.batch_size, self.seq_length]    ,   self.type_vocab_size					)

       A       :       Union[str, Any]							=						None
       A       :       Tuple							=						None
       A       :       Any							=						None
       if self.use_labels:
           A       :       int							=						ids_tensor([self.batch_size]    ,   self.type_sequence_label_size					)
           A       :       Dict							=						ids_tensor([self.batch_size, self.seq_length]    ,   self.num_labels					)
           A       :       Any							=						ids_tensor([self.batch_size]    ,   self.num_choices					)

       A       :       Optional[Any]							=						self.get_config()

       return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels


   def 					snake_case				( self					):
       return OpenLlamaConfig(
           vocab_size=self.vocab_size    ,   hidden_size=self.hidden_size    ,   num_hidden_layers=self.num_hidden_layers    ,   num_attention_heads=self.num_attention_heads    ,   intermediate_size=self.intermediate_size    ,   hidden_act=self.hidden_act    ,   hidden_dropout_prob=self.hidden_dropout_prob    ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,   max_position_embeddings=self.max_position_embeddings    ,   type_vocab_size=self.type_vocab_size    ,   is_decoder=_lowercase    ,   initializer_range=self.initializer_range    ,   use_stable_embedding=_lowercase    ,   )


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase					):
       A       :       Optional[int]							=						OpenLlamaModel(config=_lowercase					)
       model.to(_lowercase					)
       model.eval()
       A       :       str							=						model(_lowercase    ,   attention_mask=_lowercase					)
       A       :       Tuple							=						model(_lowercase					)
       self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)					)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   ):
       A       :       Optional[Any]							=						True
       A       :       str							=						OpenLlamaModel(_lowercase					)
       model.to(_lowercase					)
       model.eval()
       A       :       str							=						model(
           _lowercase    ,   attention_mask=_lowercase    ,   encoder_hidden_states=_lowercase    ,   encoder_attention_mask=_lowercase    ,   )
       A       :       Dict							=						model(
           _lowercase    ,   attention_mask=_lowercase    ,   encoder_hidden_states=_lowercase    ,   )
       A       :       Tuple							=						model(_lowercase    ,   attention_mask=_lowercase					)
       self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)					)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   ):
       A       :       Optional[Any]							=						OpenLlamaForCausalLM(config=_lowercase					)
       model.to(_lowercase					)
       model.eval()
       A       :       List[Any]							=						model(_lowercase    ,   attention_mask=_lowercase    ,   labels=_lowercase					)
       self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.seq_length, self.vocab_size)					)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   ):
       A       :       Any							=						True
       A       :       Any							=						True
       A       :       Tuple							=						OpenLlamaForCausalLM(config=_lowercase					)
       model.to(_lowercase					)
       model.eval()

       # first forward pass
       A       :       int							=						model(
           _lowercase    ,   attention_mask=_lowercase    ,   encoder_hidden_states=_lowercase    ,   encoder_attention_mask=_lowercase    ,   use_cache=_lowercase    ,   )
       A       :       Optional[Any]							=						outputs.past_key_values

       # create hypothetical multiple next token and extent to next_input_ids
       A       :       Any							=						ids_tensor((self.batch_size, 3)    ,   config.vocab_size					)
       A       :       Optional[Any]							=						ids_tensor((self.batch_size, 3)    ,   vocab_size=2					)

       # append to next input_ids and
       A       :       str							=						torch.cat([input_ids, next_tokens]    ,   dim=-1					)
       A       :       Optional[int]							=						torch.cat([input_mask, next_mask]    ,   dim=-1					)

       A       :       Optional[Any]							=						model(
           _lowercase    ,   attention_mask=_lowercase    ,   encoder_hidden_states=_lowercase    ,   encoder_attention_mask=_lowercase    ,   output_hidden_states=_lowercase    ,   )['hidden_states'][0]
       A       :       Union[str, Any]							=						model(
           _lowercase    ,   attention_mask=_lowercase    ,   encoder_hidden_states=_lowercase    ,   encoder_attention_mask=_lowercase    ,   past_key_values=_lowercase    ,   output_hidden_states=_lowercase    ,   )['hidden_states'][0]

       # select random slice
       A       :       Any							=						ids_tensor((1,)    ,   output_from_past.shape[-1]					).item()
       A       :       Optional[int]							=						output_from_no_past[:, -3:, random_slice_idx].detach()
       A       :       Optional[Any]							=						output_from_past[:, :, random_slice_idx].detach()

       self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]					)

       # test that outputs are equal for slice
       self.parent.assertTrue(torch.allclose(_lowercase    ,   _lowercase    ,   atol=1E-3					)					)


   def 					snake_case				( self					):
       A       :       List[Any]							=						self.prepare_config_and_inputs()
       (
           A      
       )       :       List[str]							=						config_and_inputs
       A       :       List[str]							=						{'input_ids': input_ids, 'attention_mask': input_mask}
       return config, inputs_dict







@require_torch
class   _lowercase						(							UpperCAmelCase_		,					UpperCAmelCase_		,					UpperCAmelCase_		,					unittest.TestCase				):
   _UpperCamelCase       		=   (
       (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
   )
   _UpperCamelCase       		=   (OpenLlamaForCausalLM,) if is_torch_available() else ()
   _UpperCamelCase       		=   (
       {
           'feature-extraction': OpenLlamaModel,
           'text-classification': OpenLlamaForSequenceClassification,
           'text-generation': OpenLlamaForCausalLM,
           'zero-shot': OpenLlamaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _UpperCamelCase       		=   False
   _UpperCamelCase       		=   False


   def 					snake_case				( self					):
       A       :       str							=						OpenLlamaModelTester(self					)
       A       :       List[Any]							=						ConfigTester(self    ,   config_class=_lowercase    ,   hidden_size=37					)


   def 					snake_case				( self					):
       self.config_tester.run_common_tests()


   def 					snake_case				( self					):
       A       :       List[str]							=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowercase					)


   def 					snake_case				( self					):
       A       :       List[Any]							=						self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
           A       :       Union[str, Any]							=						type
           self.model_tester.create_and_check_model(*_lowercase					)


   def 					snake_case				( self					):
       A       :       int							=						self.model_tester.prepare_config_and_inputs_for_common()
       A       :       str							=						3
       A       :       Optional[int]							=						input_dict['input_ids']
       A       :       str							=						input_ids.ne(1					).to(_lowercase					)
       A       :       Tuple							=						ids_tensor([self.model_tester.batch_size]    ,   self.model_tester.type_sequence_label_size					)
       A       :       Dict							=						OpenLlamaForSequenceClassification(_lowercase					)
       model.to(_lowercase					)
       model.eval()
       A       :       Optional[int]							=						model(_lowercase    ,   attention_mask=_lowercase    ,   labels=_lowercase					)
       self.assertEqual(result.logits.shape    ,   (self.model_tester.batch_size, self.model_tester.num_labels)					)


   def 					snake_case				( self					):
       A       :       int							=						self.model_tester.prepare_config_and_inputs_for_common()
       A       :       Optional[int]							=						3
       A       :       Union[str, Any]							=						'single_label_classification'
       A       :       List[str]							=						input_dict['input_ids']
       A       :       Union[str, Any]							=						input_ids.ne(1					).to(_lowercase					)
       A       :       int							=						ids_tensor([self.model_tester.batch_size]    ,   self.model_tester.type_sequence_label_size					)
       A       :       List[Any]							=						OpenLlamaForSequenceClassification(_lowercase					)
       model.to(_lowercase					)
       model.eval()
       A       :       List[str]							=						model(_lowercase    ,   attention_mask=_lowercase    ,   labels=_lowercase					)
       self.assertEqual(result.logits.shape    ,   (self.model_tester.batch_size, self.model_tester.num_labels)					)


   def 					snake_case				( self					):
       A       :       Dict							=						self.model_tester.prepare_config_and_inputs_for_common()
       A       :       Optional[Any]							=						3
       A       :       int							=						'multi_label_classification'
       A       :       Tuple							=						input_dict['input_ids']
       A       :       List[str]							=						input_ids.ne(1					).to(_lowercase					)
       A       :       Optional[int]							=						ids_tensor(
           [self.model_tester.batch_size, config.num_labels]    ,   self.model_tester.type_sequence_label_size					).to(torch.float					)
       A       :       Dict							=						OpenLlamaForSequenceClassification(_lowercase					)
       model.to(_lowercase					)
       model.eval()
       A       :       Tuple							=						model(_lowercase    ,   attention_mask=_lowercase    ,   labels=_lowercase					)
       self.assertEqual(result.logits.shape    ,   (self.model_tester.batch_size, self.model_tester.num_labels)					)


   @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test'''					)
   def 					snake_case				( self					):
       pass


   @parameterized.expand([('''linear''',), ('''dynamic''',)]					)
   def 					snake_case				( self    ,   _UpperCAmelCase					):
       A       :       List[str]							=						self.model_tester.prepare_config_and_inputs_for_common()
       A       :       Any							=						ids_tensor([1, 10]    ,   config.vocab_size					)
       A       :       Tuple							=						ids_tensor([1, int(config.max_position_embeddings * 1.5					)]    ,   config.vocab_size					)

       set_seed(42					)  # Fixed seed at init time so the two models get the same random weights
       A       :       List[str]							=						OpenLlamaModel(_lowercase					)
       original_model.to(_lowercase					)
       original_model.eval()
       A       :       int							=						original_model(_lowercase					).last_hidden_state
       A       :       int							=						original_model(_lowercase					).last_hidden_state

       set_seed(42					)  # Fixed seed at init time so the two models get the same random weights
       A       :       Optional[Any]							=						{'type': scaling_type, 'factor': 10.0}
       A       :       str							=						OpenLlamaModel(_lowercase					)
       scaled_model.to(_lowercase					)
       scaled_model.eval()
       A       :       int							=						scaled_model(_lowercase					).last_hidden_state
       A       :       List[str]							=						scaled_model(_lowercase					).last_hidden_state

       # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
       # maximum sequence length, so the outputs for the short input should match.
       if scaling_type == "dynamic":
           self.assertTrue(torch.allclose(_lowercase    ,   _lowercase    ,   atol=1E-5					)					)
       else:
           self.assertFalse(torch.allclose(_lowercase    ,   _lowercase    ,   atol=1E-5					)					)

       # The output should be different for long inputs
       self.assertFalse(torch.allclose(_lowercase    ,   _lowercase    ,   atol=1E-5					)					)







'''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)
