BigBird

repository·master·Indexed 20 days ago

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

A sparse-attention based transformer designed to extend the context window of models like BERT to handle longer sequences and long-range dependencies more efficiently. It supports various attention types including original_full, simulated_sparse, and block_sparse, and provides pretrained checkpoints for BERT and Pegasus Encoder-Decoder models.

Tokens
4.1K
Snippets
18
Records
19
Agent score
71%

What's inside BigBird

  1. Download BigBird checkpoints

    master

    Pretrained and fine-tuned checkpoints are available in a Google Cloud Storage bucket. You can download them using gsutil into a bigbird/ckpt directory.

    Available checkpoints include:

    • Pretrained BERT models: bigbr_base (base) and bigbr_large (large). These are encoder-only models with post-normalization.
    • Pretrained Pegasus Encoder-Decoder: bigbp_large (large). These use pre-normalization and have separate encoder-decoder weights.
    • Fine-tuned tf.SavedModel: Specifically for long document summarization, suitable for direct prediction and evaluation.
    mkdir -p bigbird/ckpt
    gsutil cp -r gs://bigbird-transformer/ bigbird/ckpt/
  2. Create a GCP instance for BigBird

    master

    To run BigBird on Google Cloud, you can create a Compute Engine instance and a Cloud TPU instance. The following commands use europe-west4-a and the instance name bigbird as examples.

    Compute Instance:

    gcloud compute instances create \
      bigbird \
      --zone=europe-west4-a \
      --machine-type=n1-standard-16 \
      --boot-disk-size=50GB \
      --image-project=ml-images \
      --image-family=tf-2-3-1 \
      --maintenance-policy TERMINATE \
      --restart-on-failure \
      --scopes=cloud-platform

    Cloud TPU Instance:

    gcloud compute tpus create \
      bigbird \
      --zone=europe-west4-a \
      --accelerator-type=v3-32 \
      --version=2.3.1

    SSH into instance:

    gcloud compute ssh --zone "europe-west4-a" "bigbird"
  3. Configure BigBird attention types and parameters

    master

    BigBird's behavior is controlled via flags and configuration parameters (defined in core/flags.py).

    attention_type

    Selects the attention implementation:

    • original_full: Standard full attention (as in original BERT). Recommended for sequence lengths < 1024.
    • simulated_sparse: Simulated sparse attention.
    • block_sparse: The actual BigBird blocked sparse attention implementation.

    Key Parameters

    • block_size: Defines the size of the attention blocks.
    • num_rand_blocks: Sets the number of random blocks.

    Constraints and Requirements

    • Static Shapes: The current implementation primarily supports static tensors, as it is designed for TPUs.
    • Divisibility: The hidden dimension must be divisible by the number of attention heads.
  4. Load pretrained BigBird weights

    master

    To load weights from a checkpoint into an existing TransformerModel, use a tf.compat.v1.train.NewCheckpointReader. You must iterate through the model's trainable_weights and map them to the tensors in the checkpoint by name.

    import tensorflow as tf
    from tqdm import tqdm
    
    ckpt_path = 'gs://bigbird-transformer/summarization/pubmed/roberta/model.ckpt-300000'
    ckpt_reader = tf.compat.v1.train.NewCheckpointReader(ckpt_path)
    loaded_weights = []
    
    for v in tqdm(model.trainable_weights, position=0):
      try:
        # Attempt to get tensor by name (stripping last 2 chars from variable name)
        val = ckpt_reader.get_tensor(v.name[:-2])
      except:
        val = v.numpy()
      loaded_weights.append(val)
    
    model.set_weights(loaded_weights)
  5. Evaluate summarization performance using ROUGE scores

    master

    To evaluate the quality of generated summaries, use the rouge_score library. You can iterate through a dataset, compute scores for each prediction against the ground truth, and use a BootstrapAggregator to aggregate the results.

    from rouge_score import rouge_scorer
    from rouge_score import scoring
    from tqdm import tqdm
    
    # Initialize scorer and aggregator
    scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeLsum"], use_stemmer=True)
    aggregator = scoring.BootstrapAggregator()
    
    # Loop through dataset and aggregate scores
    for ex in tqdm(dataset.take(100), position=0):
      predicted_summary = summerize(ex[0])['pred_sent'][0]
      score = scorer.score(ex[1].numpy().decode('utf-8'), predicted_summary.numpy().decode('utf-8'))
      aggregator.add_scores(score)
    
    # Get final aggregated results
    results = aggregator.aggregate()
  6. Run BigBird classification experiments

    master

    You can run classification experiments using the scripts provided in the classifier directory. You must set your GCP project name and experiment bucket as environment variables before running the shell script.

    export GCP_PROJECT_NAME=bigbird-project  # Replace by your project name
    export GCP_EXP_BUCKET=gs://bigbird-transformer-training/  # Replace
    sh -x bigbird/classifier/base_size.sh
  7. Use BigBird Encoder instead of BERT/RoBERTa

    master

    To use the BigBird encoder directly in your own code (e.g., to replace a standard BERT encoder), import modeling from bigbird.core.

    from bigbird.core import modeling
    
    bigb_encoder = modeling.BertModel(...)

    Alternatively, you can interact with the individual layers of the BigBird encoder stack using the encoder module:

    from bigbird.core import encoder
    
    only_layers = encoder.EncoderStack(...)
  8. Configure BigBird summarization settings via FLAGS

    master

    BigBird uses a flags system for configuration. You can set parameters for the summarization task such as data directory, attention type, and sequence lengths. Common flags include:

    • data_dir: Path to the dataset (e.g., tfds://scientific_papers/pubmed).
    • attention_type: The sparsity pattern (e.g., block_sparse).
    • max_encoder_length: Maximum sequence length for the encoder.
    • max_decoder_length: Maximum sequence length for the decoder.
    • block_size: Size of the blocks used in sparse attention.
    • vocab_model_file: The vocabulary model to use (e.g., gpt2).

    After setting flags, you can convert them to a dictionary for model configuration using flags.as_dictionary().

    from bigbird.core import flags
    import sys
    
    FLAGS = flags.FLAGS
    if not hasattr(FLAGS, "f"): flags.DEFINE_string("f", "", "")
    FLAGS(sys.argv)
    
    FLAGS.data_dir = "tfds://scientific_papers/pubmed"
    FLAGS.attention_type = "block_sparse"
    FLAGS.max_encoder_length = 3072
    FLAGS.max_decoder_length = 256
    FLAGS.block_size = 64
    FLAGS.vocab_model_file = "gpt2"
    
    transformer_config = flags.as_dictionary()
  9. Configure BigBird Classifier Flags

    master

    BigBird uses a flags module to manage configuration. You can set global parameters such as data directory, attention type, and sequence length using the FLAGS object. Common flags include:

    • data_dir: Path to the dataset (e.g., tfds://imdb_reviews/plain_text).
    • attention_type: The sparsity pattern for attention (e.g., block_sparse).
    • max_encoder_length: The maximum sequence length for the encoder.
    • learning_rate: The optimizer learning rate.
    • num_train_steps: Total number of training steps.
    • vocab_model_file: The vocabulary model to use (e.g., gpt2).
    • use_gradient_checkpointing: Boolean to enable gradient checkpointing for memory efficiency.
    from bigbird.core import flags
    import sys
    
    FLAGS = flags.FLAGS
    if not hasattr(FLAGS, "f"): flags.DEFINE_string("f", "", "")
    FLAGS(sys.argv)
    
    # Example configuration
    FLAGS.data_dir = "tfds://imdb_reviews/plain_text"
    FLAGS.attention_type = "block_sparse"
    FLAGS.max_encoder_length = 4096
    FLAGS.learning_rate = 1e-5
    FLAGS.num_train_steps = 2000
    FLAGS.vocab_model_file = "gpt2"