





import argparse
import logging
import os
import re

import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    PushToHubCallback,
    TFAutoModelForMaskedLM,
    create_optimizer,
)


__lowercase  :   Optional[Any]						      =logging.getLogger(__name__)

__lowercase  :   str						      =tf.data.AUTOTUNE




def     a__ (					):






   '''simple docstring'''






   UpperCAmelCase_											=argparse.ArgumentParser(description="Train a masked language model on TPU."  )
   parser.add_argument(
       "--pretrained_model_config"  ,    type=snake_case_  ,    default="roberta-base"  ,    help="The model config to use. Note that we don't copy the model's weights, only the config!"  ,    )
   parser.add_argument(
       "--tokenizer"  ,    type=snake_case_  ,    default="unigram-tokenizer-wikitext"  ,    help="The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size."  ,    )

   parser.add_argument(
       "--per_replica_batch_size"  ,    type=snake_case_  ,    default=8  ,    help="Batch size per TPU core."  ,    )

   parser.add_argument(
       "--no_tpu"  ,    action="store_true"  ,    help="If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances."  ,    )

   parser.add_argument(
       "--tpu_name"  ,    type=snake_case_  ,    help="Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs."  ,    default="local"  ,    )

   parser.add_argument(
       "--tpu_zone"  ,    type=snake_case_  ,    help="Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes."  ,    )

   parser.add_argument(
       "--gcp_project"  ,    type=snake_case_  ,    help="Google cloud project name. Only used for non-Colab TPU nodes."  )

   parser.add_argument(
       "--bfloat16"  ,    action="store_true"  ,    help="Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU."  ,    )

   parser.add_argument(
       "--train_dataset"  ,    type=snake_case_  ,    help="Path to training dataset to load. If the path begins with `gs://`"
       " then the dataset will be loaded from a Google Cloud Storage bucket."  ,    )

   parser.add_argument(
       "--shuffle_buffer_size"  ,    type=snake_case_  ,    default=2**1_8  ,    help="Size of the shuffle buffer (in samples)"  ,    )

   parser.add_argument(
       "--eval_dataset"  ,    type=snake_case_  ,    help="Path to evaluation dataset to load. If the path begins with `gs://`"
       " then the dataset will be loaded from a Google Cloud Storage bucket."  ,    )

   parser.add_argument(
       "--num_epochs"  ,    type=snake_case_  ,    default=1  ,    help="Number of epochs to train for."  ,    )

   parser.add_argument(
       "--learning_rate"  ,    type=snake_case_  ,    default=1E-4  ,    help="Learning rate to use for training."  ,    )

   parser.add_argument(
       "--weight_decay_rate"  ,    type=snake_case_  ,    default=1E-3  ,    help="Weight decay rate to use for training."  ,    )

   parser.add_argument(
       "--max_length"  ,    type=snake_case_  ,    default=5_1_2  ,    help="Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py"  ,    )

   parser.add_argument(
       "--mlm_probability"  ,    type=snake_case_  ,    default=0.15  ,    help="Fraction of tokens to mask during training."  ,    )

   parser.add_argument("--output_dir"  ,    type=snake_case_  ,    required=snake_case_  ,    help="Path to save model checkpoints to."  )
   parser.add_argument("--hub_model_id"  ,    type=snake_case_  ,    help="Model ID to upload to on the Hugging Face Hub."  )

   UpperCAmelCase_											=parser.parse_args()
   return args




def     a__ (					lowercase__  ):






   '''simple docstring'''






   try:
      if args.tpu_name:
         UpperCAmelCase_											=tf.distribute.cluster_resolver.TPUClusterResolver(
             args.tpu_name  ,    zone=args.tpu_zone  ,    project=args.gcp_project  )
      else:
         UpperCAmelCase_											=tf.distribute.cluster_resolver.TPUClusterResolver()
   except ValueError:
      raise RuntimeError(
          "Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or "
          "--gcp_project. When running on a TPU VM, use --tpu_name local."  )

   tf.config.experimental_connect_to_cluster(snake_case_  )
   tf.tpu.experimental.initialize_tpu_system(snake_case_  )

   return tpu




def     a__ (					lowercase__  ):






   '''simple docstring'''






   UpperCAmelCase_											=0
   for file in file_list:
      UpperCAmelCase_											=file.split("/"  )[-1]
      UpperCAmelCase_											=re.search(R"-\d+-(\d+)\.tfrecord"  ,    snake_case_  ).group(1  )
      UpperCAmelCase_											=int(snake_case_  )
      num_samples += sample_count

   return num_samples




def     a__ (					lowercase__  ,    lowercase__  ,    lowercase__  ,    lowercase__  ,    lowercase__  ,    lowercase__=None  ):






   '''simple docstring'''






   UpperCAmelCase_											=count_samples(snake_case_  )
   UpperCAmelCase_											=tf.data.Dataset.from_tensor_slices(snake_case_  )
   if shuffle:
      UpperCAmelCase_											=dataset.shuffle(len(snake_case_  )  )
   UpperCAmelCase_											=tf.data.TFRecordDataset(snake_case_  ,    num_parallel_reads=snake_case_  )
   # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here
   UpperCAmelCase_											=dataset.apply(tf.data.experimental.assert_cardinality(snake_case_  )  )
   UpperCAmelCase_											=dataset.map(snake_case_  ,    num_parallel_calls=snake_case_  )
   if shuffle:
      assert shuffle_buffer_size is not None
      UpperCAmelCase_											=dataset.shuffle(args.shuffle_buffer_size  )
   UpperCAmelCase_											=dataset.batch(snake_case_  ,    drop_remainder=snake_case_  )
   UpperCAmelCase_											=dataset.map(snake_case_  ,    num_parallel_calls=snake_case_  )
   UpperCAmelCase_											=dataset.prefetch(snake_case_  )
   return dataset




def     a__ (					lowercase__  ):






   '''simple docstring'''






   if not args.no_tpu:
      UpperCAmelCase_											=initialize_tpu(snake_case_  )
      UpperCAmelCase_											=tf.distribute.TPUStrategy(snake_case_  )
   else:
      UpperCAmelCase_											=tf.distribute.OneDeviceStrategy(device="/gpu:0"  )

   if args.bfloataa:
      tf.keras.mixed_precision.set_global_policy("mixed_bfloat16"  )

   UpperCAmelCase_											=AutoTokenizer.from_pretrained(args.tokenizer  )
   UpperCAmelCase_											=AutoConfig.from_pretrained(args.pretrained_model_config  )
   UpperCAmelCase_											=tokenizer.vocab_size

   UpperCAmelCase_											=tf.io.gfile.glob(os.path.join(args.train_dataset  ,    "*.tfrecord"  )  )
   if not training_records:
      raise ValueError(F'No .tfrecord files found in {args.train_dataset}.'  )
   UpperCAmelCase_											=tf.io.gfile.glob(os.path.join(args.eval_dataset  ,    "*.tfrecord"  )  )
   if not eval_records:
      raise ValueError(F'No .tfrecord files found in {args.eval_dataset}.'  )

   UpperCAmelCase_											=count_samples(snake_case_  )

   UpperCAmelCase_											=num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync)
   UpperCAmelCase_											=steps_per_epoch * args.num_epochs

   with strategy.scope():
      UpperCAmelCase_											=TFAutoModelForMaskedLM.from_config(snake_case_  )
      model(model.dummy_inputs  )  # Pass some dummy inputs through the model to ensure all the weights are built
      UpperCAmelCase_											=create_optimizer(
          num_train_steps=snake_case_  ,    num_warmup_steps=total_train_steps // 2_0  ,    init_lr=args.learning_rate  ,    weight_decay_rate=args.weight_decay_rate  ,    )

      # Transformers models compute the right loss for their task by default when labels are passed, and will
      # use this for training unless you specify your own loss function in compile().
      model.compile(optimizer=snake_case_  ,    metrics=["accuracy"]  )

   def decode_fn(lowercase__  ):
      UpperCAmelCase_											={
          """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa  ,    shape=(args.max_length,)  ),
          """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa  ,    shape=(args.max_length,)  ),
      }
      return tf.io.parse_single_example(snake_case_  ,    snake_case_  )

   # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can
   # use their methods in our data pipeline.
   UpperCAmelCase_											=DataCollatorForLanguageModeling(
       tokenizer=snake_case_  ,    mlm_probability=args.mlm_probability  ,    mlm=snake_case_  ,    return_tensors="tf"  )

   def mask_with_collator(lowercase__  ):
      # TF really needs an isin() function
      UpperCAmelCase_											=(
          ~tf.cast(batch["attention_mask"]  ,    tf.bool  )
          | (batch["""input_ids"""] == tokenizer.cls_token_id)
          | (batch["""input_ids"""] == tokenizer.sep_token_id)
      )
      UpperCAmelCase_											=data_collator.tf_mask_tokens(
          batch["input_ids"]  ,    vocab_size=len(snake_case_  )  ,    mask_token_id=tokenizer.mask_token_id  ,    special_tokens_mask=snake_case_  ,    )
      return batch

   UpperCAmelCase_											=args.per_replica_batch_size * strategy.num_replicas_in_sync

   UpperCAmelCase_											=prepare_dataset(
       snake_case_  ,    decode_fn=snake_case_  ,    mask_fn=snake_case_  ,    batch_size=snake_case_  ,    shuffle=snake_case_  ,    shuffle_buffer_size=args.shuffle_buffer_size  ,    )

   UpperCAmelCase_											=prepare_dataset(
       snake_case_  ,    decode_fn=snake_case_  ,    mask_fn=snake_case_  ,    batch_size=snake_case_  ,    shuffle=snake_case_  ,    )

   UpperCAmelCase_											=[]
   if args.hub_model_id:
      callbacks.append(
          PushToHubCallback(output_dir=args.output_dir  ,    hub_model_id=args.hub_model_id  ,    tokenizer=snake_case_  )  )

   model.fit(
       snake_case_  ,    validation_data=snake_case_  ,    epochs=args.num_epochs  ,    callbacks=snake_case_  ,    )

   model.save_pretrained(args.output_dir  )


if __name__ == "__main__":
     __lowercase  :   str						      =parse_args()
     main(args)











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

import os
from pathlib import Path




def     a__ (					lowercase__  ,    lowercase__  ,    lowercase__  ):






   '''simple docstring'''






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

   # BLUE scores as follows:
   # "pair": [fairseq, transformers]
   UpperCAmelCase_											={
       "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"],
   }
   UpperCAmelCase_											=F'{src_lang}-{tgt_lang}'

   UpperCAmelCase_											=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(lowercase__  ,    exist_ok=lowercase__  )
   UpperCAmelCase_											=os.path.join(lowercase__  ,    "README.md"  )
   print(F'Generating {path}'  )
   with open(lowercase__  ,    "w"  ,    encoding="utf-8"  ) as f:
      f.write(lowercase__  )


# make sure we are under the root of the project
__lowercase  :   int						      =Path(__file__).resolve().parent.parent.parent
__lowercase  :   Any						      =repo_dir / """model_cards"""

for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
     __lowercase      ,			__lowercase      ,			__lowercase  :   Union[str, Any]						      =model_name.split("""-""")
     __lowercase  :   Optional[int]						      =model_cards_dir / """facebook""" / model_name
     write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)




