



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

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

   # BLUE scores as follows:
   # "pair": [fairseq, transformers]
   UpperCamelCase					:						List[Any]					=			{
       '''wmt19-de-en-6-6-base''': [0, 38.37],
       '''wmt19-de-en-6-6-big''': [0, 39.90],
   }
   UpperCamelCase					:						List[Any]					=			F"""{src_lang}-{tgt_lang}"""

   UpperCamelCase					:						Union[str, Any]					=			F"""\n---\n\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt19 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\n2 models are available:\n\n* [wmt19-de-en-6-6-big](https://huggingface.co/allenai/wmt19-de-en-6-6-big)\n* [wmt19-de-en-6-6-base](https://huggingface.co/allenai/wmt19-de-en-6-6-base)\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   |  transformers\n-------|---------\n{model_name}  |  {scores[model_name][1]}\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 wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -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/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\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=snake_case_ ,  exist_ok=snake_case_			)
   UpperCamelCase					:						Any					=			os.path.join(snake_case_ ,  'README.md'			)
   print(F"""Generating {path}"""			)
   with open(snake_case_ ,  'w' ,  encoding='utf-8'			) as f:
      f.write(snake_case_			)


# 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 ["wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big"]:
 __UpperCAmelCase      = model_cards_dir / "allenai" / model_name
 write_model_card(model_card_dir, src_lang='''de''', tgt_lang='''en''', model_name=model_name)








import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


__UpperCAmelCase      = logging.get_logger(__name__)
def 	UpperCamelCase			(     snake_case__ :					List[str] ,  snake_case__ :					str			)			->  Dict:
   UpperCamelCase					:						int					=			nn.functional.normalize(snake_case__			)
   UpperCamelCase					:						Union[str, Any]					=			nn.functional.normalize(snake_case__			)
   return torch.mm(snake_case__ ,  normalized_text_embeds.t()			)



class        lowerCAmelCase_	(						a__							):
       UpperCAmelCase__       :      int       =						CLIPConfig

       UpperCAmelCase__       :      Union[str, Any]       =						["CLIPEncoderLayer"]
       def __init__(    self,    SCREAMING_SNAKE_CASE_ )  ->	List[str]:
          super().__init__(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						int					=			CLIPVisionModel(config.vision_config )
          UpperCamelCase					:						int					=			nn.Linear(config.vision_config.hidden_size,    config.projection_dim,    bias=SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						List[Any]					=			nn.Parameter(torch.ones(17,    config.projection_dim ),    requires_grad=SCREAMING_SNAKE_CASE_ )
          UpperCamelCase					:						str					=			nn.Parameter(torch.ones(3,    config.projection_dim ),    requires_grad=SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						Dict					=			nn.Parameter(torch.ones(17 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
          UpperCamelCase					:						Optional[Any]					=			nn.Parameter(torch.ones(3 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
       @torch.no_grad()
       def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Union[str, Any]:
          UpperCamelCase					:						Optional[int]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
          UpperCamelCase					:						int					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )

          # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
          UpperCamelCase					:						Optional[Any]					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.special_care_embeds ).cpu().float().numpy()
          UpperCamelCase					:						Any					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.concept_embeds ).cpu().float().numpy()

          UpperCamelCase					:						str					=			[]
          UpperCamelCase					:						int					=			image_embeds.shape[0]
          for i in range(SCREAMING_SNAKE_CASE_ ):
             UpperCamelCase					:						Optional[int]					=			{'special_scores': {}, 'special_care': [], 'concept_scores': {}, 'bad_concepts': []}

             # increase this value to create a stronger `nfsw` filter
             # at the cost of increasing the possibility of filtering benign images
             UpperCamelCase					:						Optional[Any]					=			0.0

             for concept_idx in range(len(special_cos_dist[0] ) ):
                UpperCamelCase					:						Union[str, Any]					=			special_cos_dist[i][concept_idx]
                UpperCamelCase					:						Optional[Any]					=			self.special_care_embeds_weights[concept_idx].item()
                UpperCamelCase					:						str					=			round(concept_cos - concept_threshold + adjustment,    3 )
                if result_img["special_scores"][concept_idx] > 0:
                   result_img["special_care"].append({concept_idx, result_img['special_scores'][concept_idx]} )
                   UpperCamelCase					:						Dict					=			0.01

             for concept_idx in range(len(cos_dist[0] ) ):
                UpperCamelCase					:						List[Any]					=			cos_dist[i][concept_idx]
                UpperCamelCase					:						Optional[int]					=			self.concept_embeds_weights[concept_idx].item()
                UpperCamelCase					:						Union[str, Any]					=			round(concept_cos - concept_threshold + adjustment,    3 )
                if result_img["concept_scores"][concept_idx] > 0:
                   result_img["bad_concepts"].append(SCREAMING_SNAKE_CASE_ )

             result.append(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						int					=			[len(res['bad_concepts'] ) > 0 for res in result]

          for idx, has_nsfw_concept in enumerate(SCREAMING_SNAKE_CASE_ ):
             if has_nsfw_concept:
                if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) or torch.is_tensor(images[0] ):
                   UpperCamelCase					:						List[str]					=			torch.zeros_like(images[idx] )  # black image
                else:
                   UpperCamelCase					:						int					=			np.zeros(images[idx].shape )  # black image

          if any(SCREAMING_SNAKE_CASE_ ):
             logger.warning(
                 'Potential NSFW content was detected in one or more images. A black image will be returned instead.'
                 ' Try again with a different prompt and/or seed.' )

          return images, has_nsfw_concepts






       @torch.no_grad()
       def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Optional[int]:
          UpperCamelCase					:						Union[str, Any]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
          UpperCamelCase					:						str					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						str					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.special_care_embeds )
          UpperCamelCase					:						Any					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.concept_embeds )

          # increase this value to create a stronger `nsfw` filter
          # at the cost of increasing the possibility of filtering benign images
          UpperCamelCase					:						Dict					=			0.0

          UpperCamelCase					:						str					=			special_cos_dist - self.special_care_embeds_weights + adjustment
          # special_scores = special_scores.round(decimals=3)
          UpperCamelCase					:						List[str]					=			torch.any(special_scores > 0,    dim=1 )
          UpperCamelCase					:						List[Any]					=			special_care * 0.01
          UpperCamelCase					:						List[Any]					=			special_adjustment.unsqueeze(1 ).expand(-1,    cos_dist.shape[1] )

          UpperCamelCase					:						List[str]					=			(cos_dist - self.concept_embeds_weights) + special_adjustment
          # concept_scores = concept_scores.round(decimals=3)
          UpperCamelCase					:						Tuple					=			torch.any(concept_scores > 0,    dim=1 )

          UpperCamelCase					:						Any					=			0.0  # black image

          return images, has_nsfw_concepts



