MosaicBERT: A Bidirectional Encoder Optimized for Fast Pretraining

Jacob Portes, Alex Trott, Sam Havens, Daniel King, Abhinav Venigalla, Moin Nadeem, Nikhil Sardana, Daya Khudia, Jonathan Frankle

TL;DR

MosaicBERT modernizes the classic transformer encoder by integrating a suite of architectural and training optimizations like FlashAttention, ALiBi, and Gated Linear Units. The result is a model that can be pretrained from scratch to a competitive GLUE score in just 1.13 hours for roughly $20, making custom domain-specific encoders accessible to researchers without massive compute budgets.

What Problem Does This Paper Address?

Since its debut in 2018, BERT has become the bedrock of NLP, powering everything from search engines to vector databases. However, pretraining a BERT model from scratch has historically been a "rich researcher's game," requiring days of compute on expensive hardware. Consequently, most practitioners rely on generic, off-the-shelf weights that may not be optimal for specialized domains like medicine, law, or finance.

In the five years since BERT's release, the transformer landscape has evolved rapidly. Innovations like FlashAttention and new activation functions have become standard in Large Language Models (LLMs), but they haven't been systematically backported and optimized for the bidirectional encoder architecture. MosaicBERT fills this gap, providing a "modernized" BERT recipe optimized for speed and cost.

Methods

The authors didn't just add one trick; they overhauled the transformer block and the training recipe to maximize GPU throughput and convergence speed.

Architectural Upgrades

  • FlashAttention: An IO-aware attention implementation that significantly reduces memory reads/writes.
  • ALiBi (Attention with Linear Biases): Replaces learned positional embeddings with a simple bias, allowing the model to handle longer sequences than it saw during training.
  • Gated Linear Units (GLU): Specifically GeGLU, which adds a gating mechanism to the feedforward layers, improving model quality.
  • Dynamic Unpadding: Standard BERT wastes FLOPs processing "padding" tokens in a batch. MosaicBERT concatenates sequences to eliminate this waste.
  • Low-Precision LayerNorm: Moving LayerNorm to bfloat16 to reduce memory bandwidth bottlenecks.
Figure 1: (A) Schematic of MosaicBERT architecture (B) Pareto curves of average GLUE (dev) scores for MosaicBERT-Base and the standard BERT-Base. Error bars indicate 95% confidence interval over n=5 pretraining seeds. All training was on 8×A100-80GB GPUs. FlashAttention schematic adapted from [11], and unpadding schematic adapted from [66]).

Training Recipe Optimizations

  • 30% Masking Ratio: Increasing the Masked Language Modeling (MLM) masking from the traditional 15% to 30% was found to improve downstream accuracy.
  • Hardware-Aware Vocab: Increasing the vocabulary size to a multiple of 64 to ensure CUDA kernels run at peak efficiency.
  • Bfloat16 Precision: Using bfloat16 mixed-precision for better numerical stability and speed compared to standard float16.

Datasets

The models were pretrained on the C4 (Colossal Cleaned Common Crawl) dataset, a modern, massive web-scale corpus. Evaluation was performed using the GLUE (General Language Understanding Evaluation) benchmark, which includes tasks like MNLI (inference), QNLI (question answering), and SST-2 (sentiment analysis).

Key Insights and Ideas

  • Amdahl’s Law for Deep Learning: The authors took a holistic approach, realizing that optimizing just one part of the stack yields diminishing returns. By combining multiple optimizations that target different bottlenecks (compute, memory bandwidth, and convergence), they achieved a compound speedup.
  • The Pareto Frontier is the Gold Standard: Instead of comparing single points of accuracy, the authors used Pareto curves (Accuracy vs. Training Time). This reveals that MosaicBERT isn't just faster at the end; it is more efficient at every stage of training.
  • Bigger Isn't Always Better (Initially): A striking finding was that for short training durations (under 25 hours), MosaicBERT-Base actually outperforms MosaicBERT-Large. The larger model only becomes superior after a significant investment in training time, suggesting that for many niche tasks, a highly optimized "Base" model is the more economical choice.
Pareto curves showing MosaicBERT-Base and Large consistently outperforming standard BERT baselines across different training budgets.

Key Results

  • Speed & Cost: MosaicBERT-Base achieves an average GLUE score of 79.6 in just 1.13 hours on 8x A100 GPUs, costing approximately $20.
  • Efficiency: To reach the same accuracy as a strong BERT-Base baseline, MosaicBERT requires 2.38x less time.
  • Scaling: MosaicBERT-Large achieved a 1.47x speedup over its standard counterpart, reaching a GLUE score of 83.2 in 15.85 hours compared to 23.35 hours for the baseline.
  • Throughput: The combination of unpadding and FlashAttention led to massive gains in tokens processed per second, with Model FLOPs Utilization (MFU) reaching nearly 40% on A100s.

Limitations and Future Work

  • Scale Limits: The study focused on Base (~137M params) and Large (~430M params) scales. The authors note that stability at the >1B parameter scale remains an open question.
  • Long-Regime Pareto: While MosaicBERT is Pareto optimal in the tested range, it's possible that in extremely long training regimes (e.g., hundreds of epochs), the benefits of some architectural choices might shift.
  • Tokenizer Impact: The authors used the standard BERT tokenizer for comparison; they suggest that moving to a more modern tokenizer could yield further accuracy gains.

By open-sourcing the code and weights, the MosaicML team has provided a blueprint for any organization to build high-performance, domain-specific encoders without needing a supercomputer.

Summary updated

Abstract

Although BERT-style encoder models are heavily used in NLP research, many researchers do not pretrain their own BERTs from scratch due to the high cost of training. In the past half-decade since BERT first rose to prominence, many advances have been made with other transformer architectures and training configurations that have yet to be systematically incorporated into BERT. Here, we introduce MosaicBERT, a BERT-style encoder architecture and training recipe that is empirically optimized for fast pretraining. This efficient architecture incorporates FlashAttention, Attention with Linear Biases (ALiBi), Gated Linear Units (GLU), a module to dynamically remove padded tokens, and low precision LayerNorm into the classic transformer encoder block. The training recipe includes a 30% masking ratio for the Masked Language Modeling (MLM) objective, bfloat16 precision, and vocabulary size optimized for GPU throughput, in addition to best-practices from RoBERTa and other encoder models. When pretrained from scratch on the C4 dataset, this base model achieves a downstream average GLUE (dev) score of 79.6 in 1.13 hours on 8 A100 80 GB GPUs at a cost of roughly $20. We plot extensive accuracy vs. pretraining speed Pareto curves and show that MosaicBERT base and large are consistently Pareto optimal when compared to a competitive BERT base and large. This empirical speed up in pretraining enables researchers and engineers to pretrain custom BERT-style models at low cost instead of finetune on existing generic models. We open source our model weights and code.

Empirical ResultsBrowse all benchmarks →

BenchmarkMethodMetricScoreProtocol / Evidence
GLUE · devMosaicBERT-BaseAverage GLUE score83.2split: val
Source quote
L49: MosaicBERT-Base (ours) │ 83.2 │ 4.6 │ 8×A100-80 │ C4 │ 137M
GLUE · devBERT-Base (our benchmark)Average GLUE score83.2split: val · backbone=BERT-Base
Source quote
L53: BERT-Base (our benchmark) │ 83.2 │ 11.5 │ 8×A100-80 │ C4 │ 110M
GLUE · devMosaicBERT-BaseAverage GLUE score79.6split: val
Source quote
L45: MosaicBERT-Base (ours) │ 79.6 │ 1.13 │ 8×A100-80 │ C4 │ 137M
BibTeX
@inproceedings{portes2023mosaicbert,
  author = {Jacob Portes and Alex Trott and Sam Havens and Daniel King and Abhinav Venigalla and Moin Nadeem and Nikhil Sardana and Daya Khudia and Jonathan Frankle},
  title = {{MosaicBERT: A Bidirectional Encoder Optimized for Fast Pretraining}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2023},
  url = {https://openreview.net/forum?id=5zipcfLC2Z},
}
Figure