BLEURT Documentation

repository·master·Indexed 21 days ago

https://github.com/google-research/bleurt

A transfer learning-based metric for evaluating Natural Language Generation using a trained regression model based on BERT or RemBERT. It provides a command-line interface, a Python API via the BleurtScorer class, and a TensorFlow API for computation graphs. The library includes tools for tokenization (FullTokenizer, BasicTokenizer, WordpieceTokenizer), BERT model implementation, and support for various checkpoints including the high-accuracy BLEURT-20 and faster distilled versions like BLEURT-20-D12.

Tokens
6.1K
Snippets
19
Records
25
Agent score
74%

What's inside BLEURT

  1. Understand BLEURT Checkpoints

    master

    A BLEURT checkpoint is a self-contained folder containing a TensorFlow regression model and necessary resources. It is technically a Tensorflow SavedModel accompanied by a bleurt_config.json file.

    Checkpoints also include files required by BERT, such as a bert_config.json and a WordPiece dictionary or SentencePiece model for tokenization.

    Important: Each checkpoint represents a different model; therefore, results produced by different checkpoints are not directly comparable.

  2. Train a new metric from a BERT checkpoint

    master

    If you want to train a metric from a 'fresh' BERT checkpoint (one not yet fine-tuned on ratings), use the bleurt.finetune module with the following parameters. If you are using RemBERT, you may also specify a sentence_piece_model.

    BERT_DIR=bleurt/test_checkpoint
    BERT_CKPT=variables/variables
    python -m bleurt.finetune \
      -init_checkpoint=${BERT_DIR}/${BERT_CKPT} \
      -bert_config_file=${BERT_DIR}/bert_config.json \
      -vocab_file=${BERT_DIR}/vocab.txt \
      -model_dir=my_new_bleurt_checkpoint \
      -train_set=bleurt/test_data/ratings_train.jsonl \
      -dev_set=bleurt/test_data/ratings_dev.jsonl \
      -num_train_steps=500
  3. Select a BLEURT Checkpoint

    master

    BLEURT provides several types of checkpoints depending on your needs for accuracy versus speed:

    • BLEURT-20: The current state-of-the-art. It is a 32-layer RemBERT model fine-tuned on WMT Metrics Shared Task ratings and synthetic data. It offers the highest accuracy.

    Distilled Models (Compressed)

    If you need faster inference or lower resource usage, use the distilled versions of BLEURT-20. Note that compression is lossy, so smaller models are less accurate:

    • BLEURT-20-D12: 12 layers (167M parameters)
    • BLEURT-20-D6: 6 layers (45M parameters)
    • BLEURT-20-D3: 3 layers (30M parameters)

    Historical Checkpoints (English only)

    These are older models based on English BERT for archival purposes. They vary by the maximum number of tokens they can process (128 or 512):

    • BLEURT-Tiny (128 or 512 tokens)
    • BLEURT-Base (128 or 512 tokens)
    • BLEURT-Large (128 or 512 tokens)
  4. Download and use BLEURT-20 Checkpoints

    master

    The recommended checkpoint for accurate, multilingual results is BLEURT-20. It is a self-contained folder containing the regression model.

    To use it, download the zip, unzip it, and point your command or API to the resulting folder.

    # Download and unzip BLEURT-20
    wget https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip .
    unzip BLEURT-20.zip
    
    # Run scoring with the new checkpoint
    python -m bleurt.score_files \
      -candidate_file=bleurt/test_data/candidates \
      -reference_file=bleurt/test_data/references \
      -bleurt_checkpoint=BLEURT-20
  5. Reproduce ACL paper experiments with benchmark.py

    master

    The bleurt.wmt.benchmark script allows you to re-train BLEURT checkpoints from scratch using WMT ratings. It handles downloading, post-processing, training, and computing correlations with human ratings.

    Configuration Notes

    • Years 2018 and 2019: To match the results reported in the ACL paper, you must set -average_duplicates_on_test=False. This flag controls whether different ratings for the same reference-candidate pair are averaged (a practice introduced by WMT organizers in 2018).
    • Expected Variance: Due to differences in setup and initialization, correlation results may vary from the paper by approximately 0.001 to 0.1.
    BERT_DIR=bleurt/test_checkpoint
    BERT_CKPT=variables/variables
    python -m bleurt.wmt.benchmark \
     -train_years="2015 2016" \
     -test_years="2017" \
     -dev_ratio=0.1 \
     -model_dir=bleurt_model \
     -results_json=results.json \
     -init_checkpoint=${BERT_DIR}/${BERT_CKPT} \
     -bert_config_file=${BERT_DIR}/bert_config.json \
     -vocab_file=${BERT_DIR}/vocab.txt \
     -do_lower_case=True \
     -num_train_steps=20000
  6. Optimize BLEURT performance

    master

    You can significantly speed up BLEURT (up to 20X) by combining three optimization techniques:

    1. Batch size tuning: Increase -bleurt_batch_size (e.g., to 100 on a GPU) to process more pairs at once.
    2. Length-based batching: Use -batch_same_length=True in the CLI or use LengthBatchingBleurtScorer in the Python API to avoid wasting computation on padding tokens.
    3. Distilled models: Use smaller, compressed checkpoints (like BLEURT-20-D12) which are faster but lossy (outputs are correlated but not directly comparable to the original model).

    Example of combined optimizations:

    # Download distilled model
    wget https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip .
    unzip BLEURT-20-D12.zip
    
    # Run with all optimizations
    python -m bleurt.score_files \
      -candidate_file=bleurt/test_data/candidates \
      -reference_file=bleurt/test_data/references \
      -bleurt_batch_size=100 \
      -batch_same_length=True \
      -bleurt_checkpoint=BLEURT-20-D12
  7. Download and aggregate WMT ratings

    master

    Use the bleurt.wmt.db_builder module to download WMT Metrics Shared Task archives and aggregate them into a single JSONL file. This is useful for working with ratings that are otherwise spread across multiple archives.

    Supported years range from 2015 to 2019.

    python -m bleurt.wmt.db_builder \
      -target_language="en" \
      -rating_years="2015 2016" \
      -target_file=wmt.jsonl
  8. Install BLEURT

    master

    BLEURT requires Python 3, Tensorflow (>=1.15), and tf-slim (>=1.1). To install, clone the repository and install the local package using pip.

    You can verify your installation by running the included unit tests.

    pip install --upgrade pip
    git clone https://github.com/google-research/bleurt.git
    cd bleurt
    pip install .
    
    # Verify installation
    python -m unittest bleurt.score_test
    python -m unittest bleurt.score_not_eager_test
    python -m unittest bleurt.finetune_test
    python -m unittest bleurt.score_files_test
  9. Fine-tune an existing BLEURT checkpoint

    master

    You can fine-tune previous generation checkpoints (those based on English BERT) on your own custom ratings data using the bleurt.finetune module.

    The script tokenizes the input, serializes it into TFRecord files, and runs a training/evaluation loop. It saves the best model and exports it as a BLEURT checkpoint.

    Note: It is highly recommended to use a GPU for fine-tuning. You can visualize training progress using Tensorboard by pointing it to your model_dir.

    python -m bleurt.finetune \
      -init_bleurt_checkpoint=bleurt/test_checkpoint \
      -model_dir=my_new_bleurt_checkpoint \
      -train_set=bleurt/test_data/ratings_train.jsonl \
      -dev_set=bleurt/test_data/ratings_dev.jsonl \
      -num_train_steps=500
  10. Use the BLEURT Tensorflow API

    master

    For embedding BLEURT into a TensorFlow computation graph (e.g., for Tensorboard visualization during training), use score.create_bleurt_ops() to generate the necessary operations.

    import tensorflow as tf
    # Set tf.enable_eager_execution() if using TF 1.x.
    
    from bleurt import score
    
    references = tf.constant(["This is a test."])
    candidates = tf.constant(["This is the test."])
    
    bleurt_ops = score.create_bleurt_ops()
    bleurt_out = bleurt_ops(references=references, candidates=candidates)
    
    assert bleurt_out["predictions"].shape == (1,)
    print(bleurt_out["predictions"])
  11. Use the BLEURT Python API

    master

    To use BLEURT within a Python script, import the score module and use the BleurtScorer class. This is the recommended way for programmatic access.

    Note: BLEURT works in both eager_mode (default in TF 2.0) and tf.Session (TF 1.0).

    from bleurt import score
    
    checkpoint = "bleurt/test_checkpoint"
    references = ["This is a test."]
    candidates = ["This is the test."]
    
    scorer = score.BleurtScorer(checkpoint)
    scores = scorer.score(references=references, candidates=candidates)
    assert isinstance(scores, list) and len(scores) == 1
    print(scores)
  12. Reference: fine-tune CLI arguments

    master

    The bleurt.finetune script includes many parameters for controlling the training process. You can view the full list of available flags by running the help command. Many parameters are inherited from the BERT codebase.

    python finetune.py -helpfull