





import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD


torch.set_grad_enabled(False)
def 					_A	(		SCREAMING_SNAKE_CASE					:       Tuple	,	SCREAMING_SNAKE_CASE					:       Dict=False						):





  """simple docstring"""



  a__     : Any  =[]
  for i in range(config.num_hidden_layers						):
    # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
    rename_keys.append((f'''module.blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''')						)
    rename_keys.append((f'''module.blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''')						)
    rename_keys.append(
        (f'''module.blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''')						)
    rename_keys.append((f'''module.blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''')						)
    rename_keys.append((f'''module.blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''')						)
    rename_keys.append((f'''module.blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''')						)
    rename_keys.append((f'''module.blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''')						)
    rename_keys.append((f'''module.blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''')						)
    rename_keys.append((f'''module.blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''')						)
    rename_keys.append((f'''module.blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''')						)

  # projection layer + position embeddings
  rename_keys.extend(
      [
          ("module.cls_token", "vit.embeddings.cls_token"),
          ("module.patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"),
          ("module.patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"),
          ("module.pos_embed", "vit.embeddings.position_embeddings"),
      ]						)

  if base_model:
    # layernorm + pooler
    rename_keys.extend(
        [
            ("module.norm.weight", "layernorm.weight"),
            ("module.norm.bias", "layernorm.bias"),
        ]						)

    # if just the base model, we should remove "vit" from all keys that start with "vit"
    a__     : str  =[(pair[0], pair[1][4:]) if pair[1].startswith("vit"						) else pair for pair in rename_keys]
  else:
    # layernorm + classification head
    rename_keys.extend(
        [
            ("norm.weight", "vit.layernorm.weight"),
            ("norm.bias", "vit.layernorm.bias"),
            ("head.weight", "classifier.weight"),
            ("head.bias", "classifier.bias"),
        ]						)

  return rename_keys
def 					_A	(		SCREAMING_SNAKE_CASE					:       Optional[int]	,	SCREAMING_SNAKE_CASE					:       int	,	SCREAMING_SNAKE_CASE					:       List[str]=False						):





  """simple docstring"""



  for i in range(config.num_hidden_layers						):
    if base_model:
      a__     : Any  =""
    else:
      a__     : Optional[int]  ="vit."
    # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
    a__     : Optional[int]  =state_dict.pop(f'''module.blocks.{i}.attn.qkv.weight'''						)
    a__     : List[str]  =state_dict.pop(f'''module.blocks.{i}.attn.qkv.bias'''						)
    # next, add query, keys and values (in that order) to the state dict
    a__     : Union[str, Any]  =in_proj_weight[
        : config.hidden_size, :
    ]
    a__     : str  =in_proj_bias[: config.hidden_size]
    a__     : List[str]  =in_proj_weight[
        config.hidden_size : config.hidden_size * 2, :
    ]
    a__     : Any  =in_proj_bias[
        config.hidden_size : config.hidden_size * 2
    ]
    a__     : Any  =in_proj_weight[
        -config.hidden_size :, :
    ]
    a__     : str  =in_proj_bias[-config.hidden_size :]
def 					_A	(		SCREAMING_SNAKE_CASE					:       int						):





  """simple docstring"""



  a__     : Tuple  =["head.weight", "head.bias"]
  for k in ignore_keys:
    state_dict.pop(_lowerCamelCase	,	_lowerCamelCase						)
def 					_A	(		SCREAMING_SNAKE_CASE					:       Tuple						):





  """simple docstring"""



  a__     : List[Any]  =[
      "module.fc.fc1.weight",
      "module.fc.fc1.bias",
      "module.fc.bn1.weight",
      "module.fc.bn1.bias",
      "module.fc.bn1.running_mean",
      "module.fc.bn1.running_var",
      "module.fc.bn1.num_batches_tracked",
      "module.fc.fc2.weight",
      "module.fc.fc2.bias",
      "module.fc.bn2.weight",
      "module.fc.bn2.bias",
      "module.fc.bn2.running_mean",
      "module.fc.bn2.running_var",
      "module.fc.bn2.num_batches_tracked",
      "module.fc.fc3.weight",
      "module.fc.fc3.bias",
  ]
  for k in ignore_keys:
    state_dict.pop(_lowerCamelCase	,	_lowerCamelCase						)
def 					_A	(		SCREAMING_SNAKE_CASE					:       Optional[int]	,	SCREAMING_SNAKE_CASE					:       List[str]	,	SCREAMING_SNAKE_CASE					:       Optional[int]						):





  """simple docstring"""



  a__     : str  =dct.pop(_lowerCamelCase						)
  a__     : Union[str, Any]  =val
def 					_A	(		SCREAMING_SNAKE_CASE					:       Union[str, Any]	,	SCREAMING_SNAKE_CASE					:       Tuple						):





  """simple docstring"""



  a__     : int  =ViTMSNConfig()
  a__     : Dict  =1_000

  a__     : str  ="datasets/huggingface/label-files"
  a__     : Optional[int]  ="imagenet-1k-id2label.json"
  a__     : List[str]  =json.load(open(hf_hub_download(_lowerCamelCase	,	_lowerCamelCase						)	,	"r"						)						)
  a__     : str  ={int(_lowerCamelCase						): v for k, v in idalabel.items()}
  a__     : int  =idalabel
  a__     : List[str]  ={v: k for k, v in idalabel.items()}

  if "s16" in checkpoint_url:
    a__     : int  =384
    a__     : Optional[int]  =1_536
    a__     : str  =6
  elif "l16" in checkpoint_url:
    a__     : Optional[Any]  =1_024
    a__     : str  =4_096
    a__     : Any  =24
    a__     : Optional[int]  =16
    a__     : Union[str, Any]  =0.1
  elif "b4" in checkpoint_url:
    a__     : Optional[Any]  =4
  elif "l7" in checkpoint_url:
    a__     : str  =7
    a__     : int  =1_024
    a__     : int  =4_096
    a__     : Union[str, Any]  =24
    a__     : Optional[int]  =16
    a__     : List[Any]  =0.1

  a__     : str  =ViTMSNModel(_lowerCamelCase						)

  a__     : Union[str, Any]  =torch.hub.load_state_dict_from_url(_lowerCamelCase	,	map_location="cpu"						)["target_encoder"]

  a__     : Any  =ViTImageProcessor(size=config.image_size						)

  remove_projection_head(_lowerCamelCase						)
  a__     : Tuple  =create_rename_keys(_lowerCamelCase	,	base_model=_lowerCamelCase						)

  for src, dest in rename_keys:
    rename_key(_lowerCamelCase	,	_lowerCamelCase	,	_lowerCamelCase						)
  read_in_q_k_v(_lowerCamelCase	,	_lowerCamelCase	,	base_model=_lowerCamelCase						)

  model.load_state_dict(_lowerCamelCase						)
  model.eval()

  a__     : Any  ="http://images.cocodataset.org/val2017/000000039769.jpg"

  a__     : Tuple  =Image.open(requests.get(_lowerCamelCase	,	stream=_lowerCamelCase						).raw						)
  a__     : List[str]  =ViTImageProcessor(
      size=config.image_size	,	image_mean=_lowerCamelCase	,	image_std=_lowerCamelCase						)
  a__     : Tuple  =image_processor(images=_lowerCamelCase	,	return_tensors="pt"						)

  # forward pass
  torch.manual_seed(2						)
  a__     : Optional[int]  =model(**_lowerCamelCase						)
  a__     : List[str]  =outputs.last_hidden_state

  # The following Colab Notebook was used to generate these outputs:
  # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
  if "s16" in checkpoint_url:
    a__     : Any  =torch.tensor([[-1.0_9_1_5, -1.4_8_7_6, -1.1_8_0_9]]						)
  elif "b16" in checkpoint_url:
    a__     : Optional[Any]  =torch.tensor([[1_4.2_8_8_9, -1_8.9_0_4_5, 1_1.7_2_8_1]]						)
  elif "l16" in checkpoint_url:
    a__     : List[str]  =torch.tensor([[4_1.5_0_2_8, -2_2.8_6_8_1, 4_5.6_4_7_5]]						)
  elif "b4" in checkpoint_url:
    a__     : str  =torch.tensor([[-4.3_8_6_8, 5.2_9_3_2, -0.4_1_3_7]]						)
  else:
    a__     : Optional[int]  =torch.tensor([[-0.1_7_9_2, -0.6_4_6_5, 2.4_2_6_3]]						)

  # verify logits
  assert torch.allclose(last_hidden_state[:, 0, :3]	,	_lowerCamelCase	,	atol=1e-4						)

  print(f'''Saving model to {pytorch_dump_folder_path}'''						)
  model.save_pretrained(_lowerCamelCase						)

  print(f'''Saving image processor to {pytorch_dump_folder_path}'''						)
  image_processor.save_pretrained(_lowerCamelCase						)


if __name__ == "__main__":
     UpperCAmelCase     :     int							=	argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         """--checkpoint_url""",
         default="""https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar""",
         type=str,
         help="""URL of the checkpoint you\'d like to convert.""",
     )
     parser.add_argument(
         """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
     )

     UpperCAmelCase     :     List[Any]							=	parser.parse_args()
     convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)









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

import os
from pathlib import Path
def 					_A	(		SCREAMING_SNAKE_CASE					:       Optional[int]	,	SCREAMING_SNAKE_CASE					:       Any	,	SCREAMING_SNAKE_CASE					:       Tuple						):





  """simple docstring"""



  a__     : List[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__     : Optional[int]  =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(SCREAMING_SNAKE_CASE	,	exist_ok=SCREAMING_SNAKE_CASE						)
  a__     : Tuple  =os.path.join(SCREAMING_SNAKE_CASE	,	"README.md"						)
  print(f'''Generating {path}'''						)
  with open(SCREAMING_SNAKE_CASE	,	"w"	,	encoding="utf-8"						) as f:
    f.write(SCREAMING_SNAKE_CASE						)


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

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






