





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

import os
from pathlib import Path



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

       # BLUE scores as follows:
       # "pair": [fairseq, transformers]
       a__						:     Optional[Any]			=    {
           'wmt16-en-de-dist-12-1': [28.3, 27.52],
           'wmt16-en-de-dist-6-1': [27.4, 27.11],
           'wmt16-en-de-12-1': [26.9, 25.75],
       }
       a__						:     Any			=    F'{src_lang}-{tgt_lang}'

       a__						:     Optional[int]			=    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=A__		,				exist_ok=A__    )
       a__						:     Union[str, Any]			=    os.path.join(A__		,				'README.md'    )
       print(F'Generating {path}'    )
       with open(A__		,				'w'		,				encoding='utf-8'    ) as f:
              f.write(A__    )


# make sure we are under the root of the project
lowercase				:	Dict      						=  Path(__file__).resolve().parent.parent.parent
lowercase				:	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"]:
    lowercase				:	Any      						=  model_cards_dir / """allenai""" / model_name
    write_model_card(model_card_dir, src_lang="""en""", tgt_lang="""de""", model_name=model_name)









import argparse
import json

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

from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation



def A_     (		A__    )  ->		str:
       a__						:     Any			=    384
       if "tiny" in model_name:
              a__						:     List[Any]			=    [3, 3, 9, 3]
              a__						:     Optional[Any]			=    [96, 192, 384, 768]
       if "small" in model_name:
              a__						:     Union[str, Any]			=    [3, 3, 27, 3]
              a__						:     List[Any]			=    [96, 192, 384, 768]
       if "base" in model_name:
              a__						:     int			=    [3, 3, 27, 3]
              a__						:     List[str]			=    [128, 256, 512, 1024]
              a__						:     Optional[int]			=    512
       if "large" in model_name:
              a__						:     Optional[int]			=    [3, 3, 27, 3]
              a__						:     Any			=    [192, 384, 768, 1536]
              a__						:     int			=    768
       if "xlarge" in model_name:
              a__						:     str			=    [3, 3, 27, 3]
              a__						:     int			=    [256, 512, 1024, 2048]
              a__						:     List[str]			=    1024

       # set label information
       a__						:     int			=    150
       a__						:     List[Any]			=    'huggingface/label-files'
       a__						:     str			=    'ade20k-id2label.json'
       a__						:     Optional[int]			=    json.load(open(hf_hub_download(A__		,				A__		,				repo_type='dataset'    )		,				'r'    )    )
       a__						:     List[str]			=    {int(A__    ): v for k, v in idalabel.items()}
       a__						:     Union[str, Any]			=    {v: k for k, v in idalabel.items()}

       a__						:     List[Any]			=    ConvNextConfig(
           depths=A__		,				hidden_sizes=A__		,				out_features=['stage1', 'stage2', 'stage3', 'stage4']    )
       a__						:     Optional[int]			=    UperNetConfig(
           backbone_config=A__		,				auxiliary_in_channels=A__		,				num_labels=A__		,				idalabel=A__		,				labelaid=A__		,				)

       return config



def A_     (		A__    )  ->		Tuple:
       a__						:     Optional[int]			=    []

       # fmt: off
       # stem
       rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight')    )
       rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias')    )
       rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight')    )
       rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.bias')    )
       # stages
       for i in range(len(config.backbone_config.depths    )    ):
              for j in range(config.backbone_config.depths[i]    ):
                     rename_keys.append((F'backbone.stages.{i}.{j}.gamma', F'backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.weight', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.bias', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.bias')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.norm.weight', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.norm.bias', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.bias')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias')    )
              if i > 0:
                     rename_keys.append((F'backbone.downsample_layers.{i}.0.weight', F'backbone.encoder.stages.{i}.downsampling_layer.0.weight')    )
                     rename_keys.append((F'backbone.downsample_layers.{i}.0.bias', F'backbone.encoder.stages.{i}.downsampling_layer.0.bias')    )
                     rename_keys.append((F'backbone.downsample_layers.{i}.1.weight', F'backbone.encoder.stages.{i}.downsampling_layer.1.weight')    )
                     rename_keys.append((F'backbone.downsample_layers.{i}.1.bias', F'backbone.encoder.stages.{i}.downsampling_layer.1.bias')    )

              rename_keys.append((F'backbone.norm{i}.weight', F'backbone.hidden_states_norms.stage{i+1}.weight')    )
              rename_keys.append((F'backbone.norm{i}.bias', F'backbone.hidden_states_norms.stage{i+1}.bias')    )

       # decode head
       rename_keys.extend(
           [
               ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'),
               ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'),
               ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'),
               ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'),
           ]    )
       # fmt: on

       return rename_keys



def A_     (		A__		,				A__		,				A__    )  ->		str:
       a__						:     List[str]			=    dct.pop(A__    )
       a__						:     int			=    val



def A_     (		A__		,				A__		,				A__    )  ->		str:
       a__						:     Tuple			=    {
           'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth',
           'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth',
           'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth',
           'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth',
           'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth',
       }
       a__						:     Dict			=    model_name_to_url[model_name]
       a__						:     Optional[int]			=    torch.hub.load_state_dict_from_url(A__		,				map_location='cpu'    )['state_dict']

       a__						:     List[Any]			=    get_upernet_config(A__    )
       a__						:     Dict			=    UperNetForSemanticSegmentation(A__    )
       model.eval()

       # replace "bn" => "batch_norm"
       for key in state_dict.copy().keys():
              a__						:     Dict			=    state_dict.pop(A__    )
              if "bn" in key:
                     a__						:     Optional[int]			=    key.replace('bn'		,				'batch_norm'    )
              a__						:     List[Any]			=    val

       # rename keys
       a__						:     Union[str, Any]			=    create_rename_keys(A__    )
       for src, dest in rename_keys:
              rename_key(A__		,				A__		,				A__    )

       model.load_state_dict(A__    )

       # verify on image
       a__						:     str			=    'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg'
       a__						:     int			=    Image.open(requests.get(A__		,				stream=A__    ).raw    ).convert('RGB'    )

       a__						:     Union[str, Any]			=    SegformerImageProcessor()
       a__						:     Union[str, Any]			=    processor(A__		,				return_tensors='pt'    ).pixel_values

       with torch.no_grad():
              a__						:     Optional[Any]			=    model(A__    )

       if model_name == "upernet-convnext-tiny":
              a__						:     Union[str, Any]			=    torch.tensor(
                  [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]    )
       elif model_name == "upernet-convnext-small":
              a__						:     int			=    torch.tensor(
                  [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]]    )
       elif model_name == "upernet-convnext-base":
              a__						:     int			=    torch.tensor(
                  [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]]    )
       elif model_name == "upernet-convnext-large":
              a__						:     Optional[Any]			=    torch.tensor(
                  [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]]    )
       elif model_name == "upernet-convnext-xlarge":
              a__						:     Optional[int]			=    torch.tensor(
                  [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]]    )
       print('Logits:'		,				outputs.logits[0, 0, :3, :3]    )
       assert torch.allclose(outputs.logits[0, 0, :3, :3]		,				A__		,				atol=1E-4    )
       print('Looks ok!'    )

       if pytorch_dump_folder_path is not None:
              print(F'Saving model {model_name} to {pytorch_dump_folder_path}'    )
              model.save_pretrained(A__    )
              print(F'Saving processor to {pytorch_dump_folder_path}'    )
              processor.save_pretrained(A__    )

       if push_to_hub:
              print(F'Pushing model and processor for {model_name} to hub'    )
              model.push_to_hub(F'openmmlab/{model_name}'    )
              processor.push_to_hub(F'openmmlab/{model_name}'    )


if __name__ == "__main__":
    lowercase				:	Optional[Any]      						=  argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        """--model_name""",
        default="""upernet-convnext-tiny""",
        type=str,
        choices=[F"""upernet-convnext-{size}""" for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]],
        help="""Name of the ConvNext UperNet 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 or not to push the converted model to the 🤗 hub."""
    )

    lowercase				:	str      						=  parser.parse_args()
    convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)


