


# Note: if you intend to run this script make sure you look under scripts/fsmt/
# to locate the appropriate script to do the work correctly. There is a set of scripts to:
# - download and prepare data and run the conversion script
# - perform eval to get the best hparam into the config
# - generate model_cards - useful if you have multiple models from the same paper

import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname

import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary

from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging


logging.set_verbosity_warning()

__lowerCAmelCase			=							2

# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
__lowerCAmelCase			=							{
    # fairseq:
    '''wmt19-ru-en''': {'''length_penalty''': 1.1},
    '''wmt19-en-ru''': {'''length_penalty''': 1.15},
    '''wmt19-en-de''': {'''length_penalty''': 1.0},
    '''wmt19-de-en''': {'''length_penalty''': 1.1},
    # allenai:
    '''wmt16-en-de-dist-12-1''': {'''length_penalty''': 0.6},
    '''wmt16-en-de-dist-6-1''': {'''length_penalty''': 0.6},
    '''wmt16-en-de-12-1''': {'''length_penalty''': 0.8},
    '''wmt19-de-en-6-6-base''': {'''length_penalty''': 0.6},
    '''wmt19-de-en-6-6-big''': {'''length_penalty''': 0.6},
}

# this remaps the different models to their organization names
__lowerCAmelCase			=							{}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
 __lowerCAmelCase			=							'''facebook'''
for m in [
    "wmt16-en-de-dist-12-1",
    "wmt16-en-de-dist-6-1",
    "wmt16-en-de-12-1",
    "wmt19-de-en-6-6-base",
    "wmt19-de-en-6-6-big",
]:
 __lowerCAmelCase			=							'''allenai'''




def        snake_case_					(  snake_case					)  ->    Dict:
       # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up,
       # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7}
       lowercase__:       Optional[Any]        =       dict((re.sub(R'@@$'      ,							''      ,							snake_case					), v) if k.endswith('@@'					) else (re.sub(R'$'      ,							'</w>'      ,							snake_case					), v) for k, v in d.items()					)
       lowercase__:       Any        =       '<s> <pad> </s> <unk>'.split()
       # restore the special tokens
       for k in keep_keys:
              del da[f'{k}</w>']
              lowercase__:       Any        =       d[k]  # restore
       return da




def        snake_case_					(  snake_case      ,							snake_case					)  ->    Optional[Any]:
       # prep
       assert os.path.exists(snake_case					)
       os.makedirs(snake_case      ,							exist_ok=snake_case					)
       print(f'Writing results to {pytorch_dump_folder_path}'					)

       # handle various types of models

       lowercase__:       Optional[Any]        =       basename(snake_case					)
       lowercase__:       Union[str, Any]        =       dirname(snake_case					)

       lowercase__:       Optional[int]        =       fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
       lowercase__:       List[Any]        =       cls.hub_models()
       lowercase__:       Union[str, Any]        =       {'bpe': 'fastbpe', 'tokenizer': 'moses'}
       lowercase__:       Optional[Any]        =       '.'
       # note: since the model dump is old, fairseq has upgraded its model some
       # time later, and it does a whole lot of rewrites and splits on the saved
       # weights, therefore we can't use torch.load() directly on the model file.
       # see: upgrade_state_dict(state_dict) in fairseq_model.py
       print(f'using checkpoint {checkpoint_file}'					)
       lowercase__:       str        =       hub_utils.from_pretrained(
           snake_case      ,							snake_case      ,							snake_case      ,							archive_map=snake_case      ,							**snake_case					)

       lowercase__:       int        =       vars(chkpt['args']['model']					)

       lowercase__:       Optional[Any]        =       args['source_lang']
       lowercase__:       Dict        =       args['target_lang']

       lowercase__:       List[str]        =       dirname(snake_case					)
       lowercase__:       Any        =       basename(snake_case					)

       # dicts
       lowercase__:       int        =       os.path.join(snake_case      ,							f'dict.{src_lang}.txt'					)
       lowercase__:       str        =       os.path.join(snake_case      ,							f'dict.{tgt_lang}.txt'					)

       lowercase__:       List[str]        =       Dictionary.load(snake_case					)
       lowercase__:       Optional[int]        =       rewrite_dict_keys(src_dict.indices					)
       lowercase__:       Optional[int]        =       len(snake_case					)
       lowercase__:       Union[str, Any]        =       os.path.join(snake_case      ,							'vocab-src.json'					)
       print(f'Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records'					)
       with open(snake_case      ,							'w'      ,							encoding='utf-8'					) as f:
              f.write(json.dumps(snake_case      ,							ensure_ascii=snake_case      ,							indent=snake_case					)					)

       # detect whether this is a do_lower_case situation, which can be derived by checking whether we
       # have at least one uppercase letter in the source vocab
       lowercase__:       Optional[Any]        =       True
       for k in src_vocab.keys():
              if not k.islower():
                     lowercase__:       Tuple        =       False
                     break

       lowercase__:       List[Any]        =       Dictionary.load(snake_case					)
       lowercase__:       Tuple        =       rewrite_dict_keys(tgt_dict.indices					)
       lowercase__:       Dict        =       len(snake_case					)
       lowercase__:       Optional[int]        =       os.path.join(snake_case      ,							'vocab-tgt.json'					)
       print(f'Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records'					)
       with open(snake_case      ,							'w'      ,							encoding='utf-8'					) as f:
              f.write(json.dumps(snake_case      ,							ensure_ascii=snake_case      ,							indent=snake_case					)					)

       # merges_file (bpecodes)
       lowercase__:       Union[str, Any]        =       os.path.join(snake_case      ,							VOCAB_FILES_NAMES['merges_file']					)
       for fn in ["bpecodes", "code"]:  # older fairseq called the merges file "code"
              lowercase__:       Tuple        =       os.path.join(snake_case      ,							snake_case					)
              if os.path.exists(snake_case					):
                     break
       with open(snake_case      ,							encoding='utf-8'					) as fin:
              lowercase__:       Optional[int]        =       fin.read()
       lowercase__:       List[str]        =       re.sub(R' \d+$'      ,							''      ,							snake_case      ,							0      ,							re.M					)  # remove frequency number
       print(f'Generating {merges_file}'					)
       with open(snake_case      ,							'w'      ,							encoding='utf-8'					) as fout:
              fout.write(snake_case					)

       # model config
       lowercase__:       Any        =       os.path.join(snake_case      ,							'config.json'					)

       # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
       # may have to modify the tokenizer if a different type is used by a future model
       assert args["bpe"] == "fastbpe", f'need to extend tokenizer to support bpe={args["bpe"]}'
       assert args["tokenizer"] == "moses", f'need to extend tokenizer to support bpe={args["tokenizer"]}'

       lowercase__:       Optional[Any]        =       {
           'architectures': ['FSMTForConditionalGeneration'],
           'model_type': 'fsmt',
           'activation_dropout': args['activation_dropout'],
           'activation_function': 'relu',
           'attention_dropout': args['attention_dropout'],
           'd_model': args['decoder_embed_dim'],
           'dropout': args['dropout'],
           'init_std': 0.0_2,
           'max_position_embeddings': args['max_source_positions'],
           'num_hidden_layers': args['encoder_layers'],
           'src_vocab_size': src_vocab_size,
           'tgt_vocab_size': tgt_vocab_size,
           'langs': [src_lang, tgt_lang],
           'encoder_attention_heads': args['encoder_attention_heads'],
           'encoder_ffn_dim': args['encoder_ffn_embed_dim'],
           'encoder_layerdrop': args['encoder_layerdrop'],
           'encoder_layers': args['encoder_layers'],
           'decoder_attention_heads': args['decoder_attention_heads'],
           'decoder_ffn_dim': args['decoder_ffn_embed_dim'],
           'decoder_layerdrop': args['decoder_layerdrop'],
           'decoder_layers': args['decoder_layers'],
           'bos_token_id': 0,
           'pad_token_id': 1,
           'eos_token_id': 2,
           'is_encoder_decoder': True,
           'scale_embedding': not args['no_scale_embedding'],
           'tie_word_embeddings': args['share_all_embeddings'],
       }

       # good hparam defaults to start with
       lowercase__:       Union[str, Any]        =       5
       lowercase__:       List[Any]        =       False
       if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
              lowercase__:       Tuple        =       best_score_hparams[model_dir]['length_penalty']
       else:
              lowercase__:       Union[str, Any]        =       1.0

       print(f'Generating {fsmt_model_config_file}'					)
       with open(snake_case      ,							'w'      ,							encoding='utf-8'					) as f:
              f.write(json.dumps(snake_case      ,							ensure_ascii=snake_case      ,							indent=snake_case					)					)

       # tokenizer config
       lowercase__:       Optional[int]        =       os.path.join(snake_case      ,							snake_case					)

       lowercase__:       Any        =       {
           'langs': [src_lang, tgt_lang],
           'model_max_length': 10_24,
           'do_lower_case': do_lower_case,
       }

       print(f'Generating {fsmt_tokenizer_config_file}'					)
       with open(snake_case      ,							'w'      ,							encoding='utf-8'					) as f:
              f.write(json.dumps(snake_case      ,							ensure_ascii=snake_case      ,							indent=snake_case					)					)

       # model
       lowercase__:       int        =       chkpt['models'][0]
       lowercase__:       Optional[int]        =       model.state_dict()

       # rename keys to start with 'model.'
       lowercase__:       List[str]        =       OrderedDict(('model.' + k, v) for k, v in model_state_dict.items()					)

       # remove unneeded keys
       lowercase__:       int        =       [
           'model.model',
           'model.encoder.version',
           'model.decoder.version',
           'model.encoder_embed_tokens.weight',
           'model.decoder_embed_tokens.weight',
           'model.encoder.embed_positions._float_tensor',
           'model.decoder.embed_positions._float_tensor',
       ]
       for k in ignore_keys:
              model_state_dict.pop(snake_case      ,							snake_case					)

       lowercase__:       Dict        =       FSMTConfig.from_pretrained(snake_case					)
       lowercase__:       Union[str, Any]        =       FSMTForConditionalGeneration(snake_case					)

       # check that it loads ok
       model_new.load_state_dict(snake_case      ,							strict=snake_case					)

       # save
       lowercase__:       Tuple        =       os.path.join(snake_case      ,							snake_case					)
       print(f'Generating {pytorch_weights_dump_path}'					)
       torch.save(snake_case      ,							snake_case					)

       print('Conversion is done!'					)
       print('\nLast step is to upload the files to s3'					)
       print(f'cd {data_root}'					)
       print(f'transformers-cli upload {model_dir}'					)


if __name__ == "__main__":
 __lowerCAmelCase			=							argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '''--fsmt_checkpoint_path''',
     default=None,
     type=str,
     required=True,
     help=(
         '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,'''
         ''' bpecodes, etc.'''
     ),
 )
 parser.add_argument(
     '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
 )
 __lowerCAmelCase			=							parser.parse_args()
 convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)






import argparse
import os
import re

import tensorflow as tf
import torch

from transformers import BertConfig, BertModel
from transformers.utils import logging


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




def        snake_case_					(  snake_case      ,							snake_case      ,							snake_case					)  ->    Any:
       lowercase__:       Dict        =       os.path.abspath(snake_case					)
       logger.info(f'Converting TensorFlow checkpoint from {tf_path}'					)
       # Load weights from TF model
       lowercase__:       Optional[Any]        =       tf.train.list_variables(snake_case					)
       lowercase__:       List[Any]        =       []
       lowercase__:       Tuple        =       []
       lowercase__:       int        =       []
       for full_name, shape in init_vars:
              # logger.info(f"Loading TF weight {name} with shape {shape}")
              lowercase__:       Union[str, Any]        =       full_name.split('/'					)
              if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]:
                     logger.info(f'Skipping non-model layer {full_name}'					)
                     continue
              if "optimizer" in full_name:
                     logger.info(f'Skipping optimization layer {full_name}'					)
                     continue
              if name[0] == "model":
                     # ignore initial 'model'
                     lowercase__:       str        =       name[1:]
              # figure out how many levels deep the name is
              lowercase__:       Optional[Any]        =       0
              for _name in name:
                     if _name.startswith('layer_with_weights'					):
                            depth += 1
                     else:
                            break
              layer_depth.append(snake_case					)
              # read data
              lowercase__:       Optional[Any]        =       tf.train.load_variable(snake_case      ,							snake_case					)
              names.append('/'.join(snake_case					)					)
              arrays.append(snake_case					)
       logger.info(f'Read a total of {len(snake_case					):,} layers'					)

       # Sanity check
       if len(set(snake_case					)					) != 1:
              raise ValueError(f'Found layer names with different depths (layer depth {list(set(snake_case					)					)})'					)
       lowercase__:       Any        =       list(set(snake_case					)					)[0]
       if layer_depth != 1:
              raise ValueError(
                  'The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP'
                  ' heads.'					)

       # convert layers
       logger.info('Converting weights...'					)
       for full_name, array in zip(snake_case      ,							snake_case					):
              lowercase__:       Optional[int]        =       full_name.split('/'					)
              lowercase__:       List[Any]        =       model
              lowercase__:       Any        =       []
              for i, m_name in enumerate(snake_case					):
                     if m_name == ".ATTRIBUTES":
                            # variable names end with .ATTRIBUTES/VARIABLE_VALUE
                            break
                     if m_name.startswith('layer_with_weights'					):
                            lowercase__:       Any        =       int(m_name.split('-'					)[-1]					)
                            if layer_num <= 2:
                                   # embedding layers
                                   # layer_num 0: word_embeddings
                                   # layer_num 1: position_embeddings
                                   # layer_num 2: token_type_embeddings
                                   continue
                            elif layer_num == 3:
                                   # embedding LayerNorm
                                   trace.extend(['embeddings', 'LayerNorm']					)
                                   lowercase__:       str        =       getattr(snake_case      ,							'embeddings'					)
                                   lowercase__:       int        =       getattr(snake_case      ,							'LayerNorm'					)
                            elif layer_num > 3 and layer_num < config.num_hidden_layers + 4:
                                   # encoder layers
                                   trace.extend(['encoder', 'layer', str(layer_num - 4					)]					)
                                   lowercase__:       int        =       getattr(snake_case      ,							'encoder'					)
                                   lowercase__:       List[str]        =       getattr(snake_case      ,							'layer'					)
                                   lowercase__:       Union[str, Any]        =       pointer[layer_num - 4]
                            elif layer_num == config.num_hidden_layers + 4:
                                   # pooler layer
                                   trace.extend(['pooler', 'dense']					)
                                   lowercase__:       Tuple        =       getattr(snake_case      ,							'pooler'					)
                                   lowercase__:       Tuple        =       getattr(snake_case      ,							'dense'					)
                     elif m_name == "embeddings":
                            trace.append('embeddings'					)
                            lowercase__:       Union[str, Any]        =       getattr(snake_case      ,							'embeddings'					)
                            if layer_num == 0:
                                   trace.append('word_embeddings'					)
                                   lowercase__:       Union[str, Any]        =       getattr(snake_case      ,							'word_embeddings'					)
                            elif layer_num == 1:
                                   trace.append('position_embeddings'					)
                                   lowercase__:       Dict        =       getattr(snake_case      ,							'position_embeddings'					)
                            elif layer_num == 2:
                                   trace.append('token_type_embeddings'					)
                                   lowercase__:       Optional[Any]        =       getattr(snake_case      ,							'token_type_embeddings'					)
                            else:
                                   raise ValueError(f'Unknown embedding layer with name {full_name}'					)
                            trace.append('weight'					)
                            lowercase__:       List[str]        =       getattr(snake_case      ,							'weight'					)
                     elif m_name == "_attention_layer":
                            # self-attention layer
                            trace.extend(['attention', 'self']					)
                            lowercase__:       int        =       getattr(snake_case      ,							'attention'					)
                            lowercase__:       Union[str, Any]        =       getattr(snake_case      ,							'self'					)
                     elif m_name == "_attention_layer_norm":
                            # output attention norm
                            trace.extend(['attention', 'output', 'LayerNorm']					)
                            lowercase__:       str        =       getattr(snake_case      ,							'attention'					)
                            lowercase__:       Optional[Any]        =       getattr(snake_case      ,							'output'					)
                            lowercase__:       List[Any]        =       getattr(snake_case      ,							'LayerNorm'					)
                     elif m_name == "_attention_output_dense":
                            # output attention dense
                            trace.extend(['attention', 'output', 'dense']					)
                            lowercase__:       Optional[Any]        =       getattr(snake_case      ,							'attention'					)
                            lowercase__:       Optional[int]        =       getattr(snake_case      ,							'output'					)
                            lowercase__:       Optional[Any]        =       getattr(snake_case      ,							'dense'					)
                     elif m_name == "_output_dense":
                            # output dense
                            trace.extend(['output', 'dense']					)
                            lowercase__:       Union[str, Any]        =       getattr(snake_case      ,							'output'					)
                            lowercase__:       List[Any]        =       getattr(snake_case      ,							'dense'					)
                     elif m_name == "_output_layer_norm":
                            # output dense
                            trace.extend(['output', 'LayerNorm']					)
                            lowercase__:       Any        =       getattr(snake_case      ,							'output'					)
                            lowercase__:       str        =       getattr(snake_case      ,							'LayerNorm'					)
                     elif m_name == "_key_dense":
                            # attention key
                            trace.append('key'					)
                            lowercase__:       Tuple        =       getattr(snake_case      ,							'key'					)
                     elif m_name == "_query_dense":
                            # attention query
                            trace.append('query'					)
                            lowercase__:       List[str]        =       getattr(snake_case      ,							'query'					)
                     elif m_name == "_value_dense":
                            # attention value
                            trace.append('value'					)
                            lowercase__:       Optional[int]        =       getattr(snake_case      ,							'value'					)
                     elif m_name == "_intermediate_dense":
                            # attention intermediate dense
                            trace.extend(['intermediate', 'dense']					)
                            lowercase__:       Any        =       getattr(snake_case      ,							'intermediate'					)
                            lowercase__:       str        =       getattr(snake_case      ,							'dense'					)
                     elif m_name == "_output_layer_norm":
                            # output layer norm
                            trace.append('output'					)
                            lowercase__:       Union[str, Any]        =       getattr(snake_case      ,							'output'					)
                     # weights & biases
                     elif m_name in ["bias", "beta"]:
                            trace.append('bias'					)
                            lowercase__:       str        =       getattr(snake_case      ,							'bias'					)
                     elif m_name in ["kernel", "gamma"]:
                            trace.append('weight'					)
                            lowercase__:       Tuple        =       getattr(snake_case      ,							'weight'					)
                     else:
                            logger.warning(f'Ignored {m_name}'					)
        # for certain layers reshape is necessary
              lowercase__:       Any        =       '.'.join(snake_case					)
              if re.match(R'(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)'      ,							snake_case					) or re.match(
                  R'(\S+)\.attention\.output\.dense\.weight'      ,							snake_case					):
                     lowercase__:       Union[str, Any]        =       array.reshape(pointer.data.shape					)
              if "kernel" in full_name:
                     lowercase__:       str        =       array.transpose()
              if pointer.shape == array.shape:
                     lowercase__:       Union[str, Any]        =       torch.from_numpy(snake_case					)
              else:
                     raise ValueError(
                         f'Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:'
                         f' {array.shape}'					)
              logger.info(f'Successfully set variable {full_name} to PyTorch layer {trace}'					)
       return model




def        snake_case_					(  snake_case      ,							snake_case      ,							snake_case					)  ->    Any:
       # Instantiate model
       logger.info(f'Loading model based on config from {config_path}...'					)
       lowercase__:       int        =       BertConfig.from_json_file(snake_case					)
       lowercase__:       Tuple        =       BertModel(snake_case					)

       # Load weights from checkpoint
       logger.info(f'Loading weights from checkpoint {tf_checkpoint_path}...'					)
       load_tfa_weights_in_bert(snake_case      ,							snake_case      ,							snake_case					)

       # Save pytorch-model
       logger.info(f'Saving PyTorch model to {pytorch_dump_path}...'					)
       torch.save(model.state_dict()      ,							snake_case					)


if __name__ == "__main__":
 __lowerCAmelCase			=							argparse.ArgumentParser()
 parser.add_argument(
     '''--tf_checkpoint_path''', type=str, required=True, help='''Path to the TensorFlow 2.x checkpoint path.'''
 )
 parser.add_argument(
     '''--bert_config_file''',
     type=str,
     required=True,
     help='''The config json file corresponding to the BERT model. This specifies the model architecture.''',
 )
 parser.add_argument(
     '''--pytorch_dump_path''',
     type=str,
     required=True,
     help='''Path to the output PyTorch model (must include filename).''',
 )
 __lowerCAmelCase			=							parser.parse_args()
 convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)


