



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

import os
from pathlib import Path






def 				A				(					_lowerCamelCase				, _lowerCamelCase				, _lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase     :							Optional[int]    =    {
							    "en": "Machine learning is great, isn't it?",
							    "ru": "Машинное обучение - это здорово, не так ли?",
							    "de": "Maschinelles Lernen ist großartig, oder?",
							}

							# BLUE scores as follows:
							# "pair": [fairseq, transformers]
							_lowerCAmelCase     :							Tuple    =    {
							    "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"],
							}
							_lowerCAmelCase     :							Union[str, Any]    =    F"{src_lang}-{tgt_lang}"

							_lowerCAmelCase     :							Optional[int]    =    F"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\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 wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\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- 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)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair   | fairseq | transformers\n-------|---------|----------\n{pair}  | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\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=15\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 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\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\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```bibtex\n@inproceedings{{...,\n  year={{2020}},\n  title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n  author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n  booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n"
							os.makedirs(_lowerCamelCase				, exist_ok=_lowerCamelCase  )
							_lowerCAmelCase     :							Any    =    os.path.join(_lowerCamelCase				, "README.md"  )
							print(F"Generating {path}"  )
							with open(_lowerCamelCase				, "w"				, encoding="utf-8"  ) as f:
														f.write(_lowerCamelCase  )


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





import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from timm import create_model
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform

from transformers import BitConfig, BitForImageClassification, BitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging


logging.set_verbosity_info()
_snake_case		=  logging.get_logger(__name__)






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase     :							List[Any]    =    "huggingface/label-files"
							_lowerCAmelCase     :							int    =    "imagenet-1k-id2label.json"
							_lowerCAmelCase     :							Tuple    =    json.load(open(hf_hub_download(_lowerCamelCase				, _lowerCamelCase				, repo_type="dataset"  )				, "r"  )  )
							_lowerCAmelCase     :							Tuple    =    {int(_lowerCamelCase  ): v for k, v in idalabel.items()}
							_lowerCAmelCase     :							Union[str, Any]    =    {v: k for k, v in idalabel.items()}

							_lowerCAmelCase     :							Tuple    =    "std_conv" if "bit" in model_name else False

							# note that when using BiT as backbone for ViT-hybrid checkpoints,
							# one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same",
							# config.conv_layer = "std_conv_same"
							_lowerCAmelCase     :							Optional[int]    =    BitConfig(
							    conv_layer=_lowerCamelCase				, num_labels=1_000				, idalabel=_lowerCamelCase				, labelaid=_lowerCamelCase				, )

							return config






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							if "stem.conv" in name:
														_lowerCAmelCase     :							List[str]    =    name.replace("stem.conv"				, "bit.embedder.convolution"  )
							if "blocks" in name:
														_lowerCAmelCase     :							Any    =    name.replace("blocks"				, "layers"  )
							if "head.fc" in name:
														_lowerCAmelCase     :							Optional[Any]    =    name.replace("head.fc"				, "classifier.1"  )
							if name.startswith("norm"  ):
														_lowerCAmelCase     :							Any    =    "bit." + name
							if "bit" not in name and "classifier" not in name:
														_lowerCAmelCase     :							Dict    =    "bit.encoder." + name

							return name






def 				A				(					):





							'''simple docstring'''




							_lowerCAmelCase     :							Tuple    =    "http://images.cocodataset.org/val2017/000000039769.jpg"
							_lowerCAmelCase     :							Optional[int]    =    Image.open(requests.get(_lowerCamelCase				, stream=_lowerCamelCase  ).raw  )
							return im






@torch.no_grad()
def 				A				(					_lowerCamelCase				, _lowerCamelCase				, _lowerCamelCase=False  ):





							'''simple docstring'''




							_lowerCAmelCase     :							Dict    =    get_config(_lowerCamelCase  )

							# load original model from timm
							_lowerCAmelCase     :							int    =    create_model(_lowerCamelCase				, pretrained=_lowerCamelCase  )
							timm_model.eval()

							# load state_dict of original model
							_lowerCAmelCase     :							Any    =    timm_model.state_dict()
							for key in state_dict.copy().keys():
														_lowerCAmelCase     :							Dict    =    state_dict.pop(_lowerCamelCase  )
														_lowerCAmelCase     :							Tuple    =    val.squeeze() if "head" in key else val

							# load HuggingFace model
							_lowerCAmelCase     :							Optional[Any]    =    BitForImageClassification(_lowerCamelCase  )
							model.eval()
							model.load_state_dict(_lowerCamelCase  )

							# create image processor
							_lowerCAmelCase     :							Dict    =    create_transform(**resolve_data_config({}				, model=_lowerCamelCase  )  )
							_lowerCAmelCase     :							Optional[int]    =    transform.transforms

							_lowerCAmelCase     :							Tuple    =    {
							    "bilinear": PILImageResampling.BILINEAR,
							    "bicubic": PILImageResampling.BICUBIC,
							    "nearest": PILImageResampling.NEAREST,
							}

							_lowerCAmelCase     :							Tuple    =    BitImageProcessor(
							    do_resize=_lowerCamelCase				, size={"shortest_edge": timm_transforms[0].size}				, resample=pillow_resamplings[timm_transforms[0].interpolation.value]				, do_center_crop=_lowerCamelCase				, crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]}				, do_normalize=_lowerCamelCase				, image_mean=timm_transforms[-1].mean.tolist()				, image_std=timm_transforms[-1].std.tolist()				, )

							_lowerCAmelCase     :							Optional[int]    =    prepare_img()
							_lowerCAmelCase     :							Any    =    transform(_lowerCamelCase  ).unsqueeze(0  )
							_lowerCAmelCase     :							Optional[int]    =    processor(_lowerCamelCase				, return_tensors="pt"  ).pixel_values

							# verify pixel values
							assert torch.allclose(_lowerCamelCase				, _lowerCamelCase  )

							# verify logits
							with torch.no_grad():
														_lowerCAmelCase     :							Tuple    =    model(_lowerCamelCase  )
														_lowerCAmelCase     :							str    =    outputs.logits

							print("Logits:"				, logits[0, :3]  )
							print("Predicted class:"				, model.config.idalabel[logits.argmax(-1  ).item()]  )
							_lowerCAmelCase     :							Union[str, Any]    =    timm_model(_lowerCamelCase  )
							assert timm_logits.shape == outputs.logits.shape
							assert torch.allclose(_lowerCamelCase				, outputs.logits				, atol=1e-3  )
							print("Looks ok!"  )

							if pytorch_dump_folder_path is not None:
														Path(_lowerCamelCase  ).mkdir(exist_ok=_lowerCamelCase  )
														print(F"Saving model {model_name} and processor to {pytorch_dump_folder_path}"  )
														model.save_pretrained(_lowerCamelCase  )
														processor.save_pretrained(_lowerCamelCase  )

							if push_to_hub:
														print(F"Pushing model {model_name} and processor to the hub"  )
														model.push_to_hub(F"ybelkada/{model_name}"  )
														processor.push_to_hub(F"ybelkada/{model_name}"  )


if __name__ == "__main__":
						_snake_case		=  argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    "--model_name",
						    default="resnetv2_50x1_bitm",
						    type=str,
						    help="Name of the BiT timm model you'd like to convert.",
						)
						parser.add_argument(
						    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
						)
						parser.add_argument(
						    "--push_to_hub",
						    action="store_true",
						    help="Whether to push the model to the hub.",
						)

						_snake_case		=  parser.parse_args()
						convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
