




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

import os
from pathlib import Path

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Optional[int]			,			__UpperCAmelCase						:	List[str]			,			__UpperCAmelCase						:	List[Any]			,			__UpperCAmelCase						:	int							)					-> Dict:
      SCREAMING_SNAKE_CASE_							=			{
          'en': 'Machine learning is great, isn\'t it?',
          'ru': 'Машинное обучение - это здорово, не так ли?',
          'de': 'Maschinelles Lernen ist großartig, nicht wahr?',
      }

      # BLUE scores as follows:
      # "pair": [fairseq, transformers]
      SCREAMING_SNAKE_CASE_							=			{
          'wmt16-en-de-dist-12-1': [2_8.3, 2_7.5_2],
          'wmt16-en-de-dist-6-1': [2_7.4, 2_7.1_1],
          'wmt16-en-de-12-1': [2_6.9, 2_5.7_5],
      }
      SCREAMING_SNAKE_CASE_							=			f"{src_lang}-{tgt_lang}"

      SCREAMING_SNAKE_CASE_							=			f"\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel   | fairseq | transformers\n-------|---------|----------\n{model_name}  | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe 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.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"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\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n    year={{2020}},\n    eprint={{2006.10369}},\n    archivePrefix={{arXiv}},\n    primaryClass={{cs.CL}}\n}}\n```\n\n"
      model_card_dir.mkdir(parents=__UpperCAmelCase			,			exist_ok=__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_							=			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
lowerCamelCase__ :   Union[str, Any]					=							Path(__file__).resolve().parent.parent.parent
lowerCamelCase__ :   Tuple					=							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"]:
   lowerCamelCase__ :   List[Any]					=							model_cards_dir / 'allenai' / model_name
   write_model_card(model_card_dir, src_lang='en', tgt_lang='de', model_name=model_name)





from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import (
       TFDeiTForImageClassification,
       TFDeiTForImageClassificationWithTeacher,
       TFDeiTForMaskedImageModeling,
       TFDeiTModel,
   )
   from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import DeiTImageProcessor





class        lowerCamelCase_							:


 '''simple docstring'''







 def __init__(							self  :		Any				,				_lowerCAmelCase  :		str				,				_lowerCAmelCase  :		Tuple=13				,				_lowerCAmelCase  :		Dict=30				,				_lowerCAmelCase  :		Tuple=2				,				_lowerCAmelCase  :		Dict=3				,				_lowerCAmelCase  :		Dict=True				,				_lowerCAmelCase  :		List[str]=True				,				_lowerCAmelCase  :		int=32				,				_lowerCAmelCase  :		List[Any]=2				,				_lowerCAmelCase  :		Tuple=4				,				_lowerCAmelCase  :		Optional[int]=37				,				_lowerCAmelCase  :		List[Any]="gelu"				,				_lowerCAmelCase  :		Optional[Any]=0.1				,				_lowerCAmelCase  :		Any=0.1				,				_lowerCAmelCase  :		Optional[Any]=10				,				_lowerCAmelCase  :		Dict=0.02				,				_lowerCAmelCase  :		Optional[Any]=3				,				_lowerCAmelCase  :		Optional[Any]=None				,				_lowerCAmelCase  :		List[Any]=2				,				):
       SCREAMING_SNAKE_CASE_							=			parent
       SCREAMING_SNAKE_CASE_							=			batch_size
       SCREAMING_SNAKE_CASE_							=			image_size
       SCREAMING_SNAKE_CASE_							=			patch_size
       SCREAMING_SNAKE_CASE_							=			num_channels
       SCREAMING_SNAKE_CASE_							=			is_training
       SCREAMING_SNAKE_CASE_							=			use_labels
       SCREAMING_SNAKE_CASE_							=			hidden_size
       SCREAMING_SNAKE_CASE_							=			num_hidden_layers
       SCREAMING_SNAKE_CASE_							=			num_attention_heads
       SCREAMING_SNAKE_CASE_							=			intermediate_size
       SCREAMING_SNAKE_CASE_							=			hidden_act
       SCREAMING_SNAKE_CASE_							=			hidden_dropout_prob
       SCREAMING_SNAKE_CASE_							=			attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE_							=			type_sequence_label_size
       SCREAMING_SNAKE_CASE_							=			initializer_range
       SCREAMING_SNAKE_CASE_							=			scope
       SCREAMING_SNAKE_CASE_							=			encoder_stride

       # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
       SCREAMING_SNAKE_CASE_							=			(image_size // patch_size) ** 2
       SCREAMING_SNAKE_CASE_							=			num_patches + 2



 def       lowerCAmelCase_  (							self  :		str						):
       SCREAMING_SNAKE_CASE_							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       SCREAMING_SNAKE_CASE_							=			None
       if self.use_labels:
             SCREAMING_SNAKE_CASE_							=			ids_tensor([self.batch_size]				,				self.type_sequence_label_size						)

       SCREAMING_SNAKE_CASE_							=			self.get_config()

       return config, pixel_values, labels



 def       lowerCAmelCase_  (							self  :		Tuple						):
       return DeiTConfig(
           image_size=self.image_size				,				patch_size=self.patch_size				,				num_channels=self.num_channels				,				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				,				is_decoder=_lowerCAmelCase				,				initializer_range=self.initializer_range				,				encoder_stride=self.encoder_stride				,				)



 def       lowerCAmelCase_  (							self  :		Union[str, Any]				,				_lowerCAmelCase  :		Optional[int]				,				_lowerCAmelCase  :		List[str]				,				_lowerCAmelCase  :		Any						):
       SCREAMING_SNAKE_CASE_							=			TFDeiTModel(config=_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			model(_lowerCAmelCase						)
       self.parent.assertEqual(result.last_hidden_state.shape				,				(self.batch_size, self.seq_length, self.hidden_size)						)



 def       lowerCAmelCase_  (							self  :		Union[str, Any]				,				_lowerCAmelCase  :		List[Any]				,				_lowerCAmelCase  :		List[str]				,				_lowerCAmelCase  :		Optional[Any]						):
       SCREAMING_SNAKE_CASE_							=			TFDeiTForMaskedImageModeling(config=_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			model(_lowerCAmelCase						)
       self.parent.assertEqual(
           result.reconstruction.shape				,				(self.batch_size, self.num_channels, self.image_size, self.image_size)						)

       # test greyscale images
       SCREAMING_SNAKE_CASE_							=			1
       SCREAMING_SNAKE_CASE_							=			TFDeiTForMaskedImageModeling(_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       SCREAMING_SNAKE_CASE_							=			model(_lowerCAmelCase						)
       self.parent.assertEqual(result.reconstruction.shape				,				(self.batch_size, 1, self.image_size, self.image_size)						)



 def       lowerCAmelCase_  (							self  :		List[str]				,				_lowerCAmelCase  :		Dict				,				_lowerCAmelCase  :		List[str]				,				_lowerCAmelCase  :		Optional[Any]						):
       SCREAMING_SNAKE_CASE_							=			self.type_sequence_label_size
       SCREAMING_SNAKE_CASE_							=			TFDeiTForImageClassification(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			model(_lowerCAmelCase				,				labels=_lowerCAmelCase						)
       self.parent.assertEqual(result.logits.shape				,				(self.batch_size, self.type_sequence_label_size)						)

       # test greyscale images
       SCREAMING_SNAKE_CASE_							=			1
       SCREAMING_SNAKE_CASE_							=			TFDeiTForImageClassification(_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       SCREAMING_SNAKE_CASE_							=			model(_lowerCAmelCase				,				labels=_lowerCAmelCase						)
       self.parent.assertEqual(result.logits.shape				,				(self.batch_size, self.type_sequence_label_size)						)




 def       lowerCAmelCase_  (							self  :		Optional[int]						):
       SCREAMING_SNAKE_CASE_							=			self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			config_and_inputs
       SCREAMING_SNAKE_CASE_							=			{'pixel_values': pixel_values}
       return config, inputs_dict





@require_tf
class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE       ,   _SCREAMING_SNAKE_CASE       ,   unittest.TestCase					):


 '''simple docstring'''







 lowercase_				    =    (
     (
         TFDeiTModel,
         TFDeiTForImageClassification,
         TFDeiTForImageClassificationWithTeacher,
         TFDeiTForMaskedImageModeling,
     )
     if is_tf_available()
     else ()
 )
 lowercase_				    =    (
     {
         "feature-extraction": TFDeiTModel,
         "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
     }
     if is_tf_available()
     else {}
 )

 lowercase_				    =    False
 lowercase_				    =    False
 lowercase_				    =    False
 lowercase_				    =    False



 def       lowerCAmelCase_  (							self  :		Union[str, Any]						):
       SCREAMING_SNAKE_CASE_							=			TFDeiTModelTester(self						)
       SCREAMING_SNAKE_CASE_							=			ConfigTester(self				,				config_class=_lowerCAmelCase				,				has_text_modality=_lowerCAmelCase				,				hidden_size=37						)



 def       lowerCAmelCase_  (							self  :		List[str]						):
       self.config_tester.run_common_tests()



 @unittest.skip(reason='DeiT does not use inputs_embeds'						)
 def       lowerCAmelCase_  (							self  :		Any						):
       pass



 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE_							=			model_class(_lowerCAmelCase						)
             self.assertIsInstance(model.get_input_embeddings()				,				(tf.keras.layers.Layer)						)
             SCREAMING_SNAKE_CASE_							=			model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(_lowerCAmelCase				,				tf.keras.layers.Dense						)						)



 def       lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE_							=			model_class(_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_							=			inspect.signature(model.call						)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             SCREAMING_SNAKE_CASE_							=			[*signature.parameters.keys()]

             SCREAMING_SNAKE_CASE_							=			['pixel_values']
             self.assertListEqual(arg_names[:1]				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		str						):
       SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Any						):
       SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Tuple				,				_lowerCAmelCase  :		str				,				_lowerCAmelCase  :		List[Any]				,				_lowerCAmelCase  :		Optional[Any]=False						):
       SCREAMING_SNAKE_CASE_							=			super()._prepare_for_class(_lowerCAmelCase				,				_lowerCAmelCase				,				return_labels=_lowerCAmelCase						)

       if return_labels:
             if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call						).parameters:
                   del inputs_dict["labels"]

       return inputs_dict




 @slow
 def       lowerCAmelCase_  (							self  :		Union[str, Any]						):
       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE_							=			TFDeiTModel.from_pretrained(_lowerCAmelCase						)
             self.assertIsNotNone(_lowerCAmelCase						)


def 					UpperCAmelCase_							(      )					-> str:
      SCREAMING_SNAKE_CASE_							=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
      return image





@require_tf
@require_vision
class        lowerCamelCase_							(      unittest.TestCase					):


 '''simple docstring'''







 @cached_property
 def       lowerCAmelCase_  (							self  :		List[str]						):
       return (
           DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224'						)
           if is_vision_available()
           else None
       )




 @slow
 def       lowerCAmelCase_  (							self  :		int						):
       SCREAMING_SNAKE_CASE_							=			TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224'						)

       SCREAMING_SNAKE_CASE_							=			self.default_image_processor
       SCREAMING_SNAKE_CASE_							=			prepare_img()
       SCREAMING_SNAKE_CASE_							=			image_processor(images=_lowerCAmelCase				,				return_tensors='tf'						)

       # forward pass
       SCREAMING_SNAKE_CASE_							=			model(**_lowerCAmelCase						)

       # verify the logits
       SCREAMING_SNAKE_CASE_							=			tf.TensorShape((1, 1_000)						)
       self.assertEqual(outputs.logits.shape				,				_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			tf.constant([-1.0266, 0.1912, -1.2861]						)

       self.assertTrue(np.allclose(outputs.logits[0, :3]				,				_lowerCAmelCase				,				atol=1E-4						)						)