AI Logic

Architectures

ALBERT

Updated:

Architecture of ALBERT. On the left, the overall pretraining flow (input of [CLS], sentence A, [SEP], sentence B; embeddings with a small dimension E; a fully connected layer expanding E to H; a repeated encoder layer with the same weights; and two outputs, sentence-order prediction and the masked language model). On the right, the three differences from BERT (splitting the embedding matrix in two, sharing weights across all layers, and replacing next-sentence prediction with sentence-order prediction)

Background and overview

ALBERT (A Lite BERT) is a language model that drastically reduces the parameters of BERT so that it can be scaled up to larger configurations. It was proposed in 2019 by Lan et al. at Google Research and the Toyota Technological Institute at Chicago, and presented at ICLR 2020.

BERT achieves better downstream results as the model grows. Once the parameter count exceeds several hundred million, however, the model no longer fits in GPU or TPU memory, and communication becomes slow when the model is split across multiple machines. ALBERT lowers this barrier with three changes:

  • Factorized embeddings: vocabulary embeddings are kept in a small dimension EE and expanded to the hidden size HH with a fully connected layer
  • Cross-layer parameter sharing: the same weights are reused in every encoder layer
  • Sentence-order prediction (SOP): BERT's "next sentence prediction" is replaced with a task of predicting whether two segments are in the correct order

As a result, ALBERT-large, which has the same shape as BERT-Large, has 18M parameters, about 1/18 of BERT-Large (334M). ALBERT-xxlarge (235M), widened to H=4096H = 4096 with the savings, uses about 70% of BERT-Large's parameters and achieved the following results at the time of the paper (all ensembles):

  • An average of 89.4 on the GLUE leaderboard
  • An F1 of 92.2 on the SQuAD v2.0 test set
  • An accuracy of 89.4% on the test set of the RACE reading comprehension task

Architecture

ALBERT's backbone is the same as BERT's: LL stacked Transformer encoder layers with GELU as the activation function. Following BERT, the intermediate feed-forward size is 4H4H and the number of heads is H/64H/64. In the figure at the top of the article, the left shows the pretraining flow and the right shows the three differences from BERT.

The main sizes in the paper are as follows.

ModelParametersLayers LLHidden size HHEmbedding dimension EEWeight sharing
BERT-base108M12768768No
BERT-large334M2410241024No
ALBERT-base12M12768128Yes
ALBERT-large18M241024128Yes
ALBERT-xlarge60M242048128Yes
ALBERT-xxlarge235M124096128Yes

ALBERT-xxlarge has 12 layers because making it 24 layers with the same settings gave almost the same results while only increasing computation.

Factorized embeddings

In BERT, the vocabulary embedding dimension EE equals the hidden size HH (E=HE = H). With a vocabulary of size VV, the embedding matrix is V×HV \times H, so widening HH increases the embedding parameters by the same factor. ALBERT first maps tokens to embeddings of a small dimension EE and then expands them to HH with a fully connected layer. The parameter count changes as follows:

O(V×H)  →  O(V×E+E×H)O(V \times H) \;\rightarrow\; O(V \times E + E \times H)

For example, with V=30,000V = 30{,}000 and H=4096H = 4096, BERT's approach needs about 123M parameters for the embeddings alone, whereas factorizing with E=128E = 128 needs only about 4.36M (30,000×128+128×409630{,}000 \times 128 + 128 \times 4096). Representing a matrix as the product of two thin matrices is the same idea as low-rank factorization.

Cross-layer parameter sharing

ALBERT shares the weights of all layers, including attention and feed-forward. This is equivalent to passing through a single encoder layer LL times, so adding layers does not add parameters. A similar idea appears in the Universal Transformer.

Sharing weights does not make every layer's input and output identical. The paper confirms that the distance and angle between each layer's input and output change more smoothly than in BERT, yet do not converge to 0 even after 24 layers. Think of it as applying the same processing repeatedly to refine the representation little by little.

Training: sentence-order prediction and pretraining setup

ALBERT's pretraining learns two tasks simultaneously: the masked language model (MLM) and sentence-order prediction (SOP).

Sentence-order prediction is a binary classification that takes a pair of segments A and B, built as follows, and predicts from the [CLS] output whether the order is correct.

  1. Take two consecutive segments A and B from the same document.
  2. For half of the examples, keep the order A → B as positive examples.
  3. For the other half, swap them to B → A as negative examples.

BERT's next sentence prediction (NSP) takes the negative B from a "different document." Segments from different documents often have completely different topics, so the model can tell them apart by topic alone without understanding the connection between sentences (coherence). Since topic cues can also be learned through the masked language model, the paper argued that NSP is too easy to be very useful. SOP negatives are the same two segments from the same document, so they cannot be distinguished by topic; the model has to learn how sentences connect.

In the masked language model, tokens are masked not one at a time but in spans of 1 to 3 words (n-grams). The length nn is chosen with the following probability (N=3N = 3):

p(n)=1/n∑k=1N1/kp(n) = \frac{1/n}{\sum_{k=1}^{N} 1/k}

Shorter spans are more likely, with probabilities of about 55%, 27%, and 18% for n=1,2,3n = 1, 2, 3.

The pretraining setup in the paper is as follows.

ItemValue
DataBooksCorpus and English Wikipedia (about 16GB). The final model also uses the same additional data as XLNet and RoBERTa
Input[CLS] A [SEP] B [SEP], up to 512 tokens (shorter sequences generated with 10% probability)
TokenizationSentencePiece (vocabulary of 30,000)
Batch4,096
OptimizerLAMB (learning rate 0.00176)
Steps125k for comparison experiments; 1M and 1.5M for the final models
Hardware64 to 512 Cloud TPU v3

The final models remove dropout. Even after 1M steps of training, the largest model did not overfit the training data, and removing dropout improved both masked language model accuracy and downstream results.

Fine-tuning is the same as in BERT: an output layer is added and the whole model is retrained. The paper's settings vary by task, with learning rates of 1×10−51 \times 10^{-5} to 5×10−55 \times 10^{-5} and batch sizes of 16 to 128.

Why does it work?

Each of ALBERT's techniques aims to decouple "the number of parameters" from "representational power."

  • Factorized embeddings: Vocabulary embeddings represent words themselves, independent of context. Hidden-layer vectors, by contrast, are context-dependent representations and need to carry more information (H≫EH \gg E). With factorization, widening HH barely increases the embedding parameters. Another reason is that vocabulary embeddings are updated only for the rows of words that appear in each training step, so making them large is inefficient.
  • Weight sharing: It stops the parameter count from growing in proportion to the number of layers. Fewer parameters mean less memory and less communication for exchanging weights between machines, so training is faster than for a BERT of the same shape (ALBERT-large is about 1.7 times as fast as BERT-Large). The paper also states that weight sharing acts like regularization and stabilizes training.
  • Sentence-order prediction: By blocking the "shortcut" of topic differences, it forces the model to learn how sentences connect. In the paper's experiments, a model trained with NSP could not solve the SOP task at all (52.0%, equal to chance), while a model trained with SOP solved the NSP task reasonably well (78.9%).

Sentence-order prediction is like a quiz asking whether two picture-story cards are in the right order. NSP asks whether the second card comes from a different story, so you can answer just by looking at the art style (the topic). SOP uses two cards from the same story, so you cannot answer without following the plot.

ALBERT reduces the number of parameters, not the amount of computation. Even with shared weights, computation is still performed for every layer. Because ALBERT-xxlarge is wide (H=4096H = 4096), it trains about 3 times slower than BERT-Large. If you need faster inference, a model that reduces the number of layers itself, such as DistilBERT, is a better fit.

Experimental results

Unless otherwise noted, the tables below show validation results for models trained for 125k steps on BooksCorpus and Wikipedia (F1 / EM for SQuAD, accuracy otherwise; Avg is the average over tasks).

BERT vs. ALBERT (Speed is training data throughput relative to BERT-Large = 1)

ModelParametersSQuAD 1.1SQuAD 2.0MNLISST-2RACEAvgSpeed
BERT-base108M90.4 / 83.280.4 / 77.684.592.868.282.34.7x
BERT-large334M92.2 / 85.585.0 / 82.286.693.073.985.21.0
ALBERT-base12M89.3 / 82.380.0 / 77.181.690.364.080.15.6x
ALBERT-large18M90.6 / 83.982.3 / 79.483.591.768.582.41.7x
ALBERT-xlarge60M92.5 / 86.186.1 / 83.186.492.474.885.50.6x
ALBERT-xxlarge235M94.1 / 88.388.1 / 85.188.095.282.388.70.3x

At the same shape (base, large), ALBERT scores slightly lower than BERT. ALBERT-xxlarge, widened by exploiting the smaller parameter count, clearly outperformed BERT-Large.

Embedding dimension EE (ALBERT-base shape)

Weight sharingEEParametersAvg
None6487M81.3
None12889M81.7
None768108M82.3
All shared6410M79.0
All shared12812M80.1
All shared76831M79.8

With weight sharing, E=128E = 128 was best, and all subsequent experiments use E=128E = 128.

What to share (ALBERT-base shape, E=128E = 128)

SharedParametersAvg
All12M80.1
Attention only64M81.7
Feed-forward only38M80.2
Not shared89M81.6

Sharing everything lowers the average by 1.5, but most of the drop comes from sharing the feed-forward layers; sharing only attention caused no drop.

Inter-sentence tasks (ALBERT-base shape; the three left columns are accuracies on the pretraining tasks themselves)

TaskMLMNSPSOPSQuAD 1.1SQuAD 2.0MNLISST-2RACEAvg
None54.952.453.388.6 / 81.578.1 / 75.381.589.961.779.0
NSP54.590.552.088.4 / 81.577.2 / 74.681.691.162.379.2
SOP54.078.986.589.3 / 82.380.0 / 77.182.090.364.080.1

SOP is especially effective on tasks with multiple sentences as input (SQuAD and RACE).

Training for the same amount of time

ModelStepsTraining timeSQuAD 1.1SQuAD 2.0MNLISST-2RACEAvg
BERT-large400k34 h93.5 / 87.486.9 / 84.387.894.677.387.2
ALBERT-xxlarge125k32 h94.0 / 88.188.3 / 85.387.895.482.588.7

Even when training time rather than step count is matched, ALBERT-xxlarge was 1.5 points higher on average.

GLUE (single model fine-tuned per task, validation data)

ModelMNLIQNLIQQPRTESST-2MRPCCoLASTS-B
BERT-large86.692.391.370.493.288.060.690.0
RoBERTa-large90.294.792.286.696.490.968.092.4
ALBERT (1M steps)90.495.292.088.196.890.268.792.7
ALBERT (1.5M steps)90.895.392.289.296.990.971.493.0

The final ALBERT has the ALBERT-xxlarge shape, is trained with MLM and SOP, and has dropout removed. On the RACE test set it scored 86.5% as a single model and 89.4% as an ensemble (RoBERTa: 83.2% as a single model).

Practical considerations

Keep the following in mind when using ALBERT.

  • Fewer parameters, but not faster: Its computation is about the same as a BERT of the same shape. Memory and storage shrink, but inference time does not. xxlarge is heavier than BERT-Large.
  • Slightly weaker than BERT at small shapes: ALBERT-base and -large score slightly lower on downstream tasks than BERT-base and -large of the same shape. ALBERT's strength is that it can scale up to wide shapes such as xxlarge with few parameters.
  • The tokenizer is SentencePiece: Its vocabulary differs from BERT's WordPiece. Use the same tokenizer as the pretrained model.
  • Input is limited to 512 tokens: As with BERT, split long documents into chunks.
  • Check the dropout settings: The paper's final models remove dropout during pretraining. For fine-tuning, dropout is set to 0 or 0.1 depending on the task (0.1 for the classification layer).

Sharing all weights gives lower results than not sharing at the same shape (average 81.6 → 80.1 with the ALBERT-base shape). Most of the drop comes from sharing the feed-forward layers. If memory allows, a compromise such as sharing only attention (average 81.7 in the paper's experiments) is also an option.

Comparison with other models

Comparing models that make BERT smaller or more efficient from the same viewpoints gives the following.

ModelWhat it reducesHowComputationPretraining tasks
BERT(baseline)—BaselineMasked language model + next sentence prediction
RoBERTaNothingImproves accuracy by revisiting the training recipeSame as BERTMasked language model only
ALBERTNumber of parametersFactorized embeddings and cross-layer parameter sharingAbout the same as BERT at the same shapeMasked language model (n-gram) + sentence-order prediction
DistilBERTNumber of layersTrains a student with half the layers via knowledge distillationLess than BERT-baseImitating the teacher and masked language model
ELECTRAPretraining computationPredicts for every token whether it was replacedSame shape as BERTReplaced token detection

Rough guidelines for choosing:

  • Limited memory or storage: ALBERT is a good fit, since it greatly reduces the parameter count.
  • Faster inference: Choose DistilBERT, which has fewer layers. ALBERT does not reduce computation, so it offers no speed advantage.
  • Higher accuracy with limited parameters: Spending the saved parameters on width, as in ALBERT-xxlarge, is effective, although computation time increases.

PyTorch example

Show code
python
import random
import torch
import torch.nn as nn

"""
A small example implementing ALBERT's two techniques (factorized embeddings and cross-layer parameter sharing) as described in the paper,
plus how to build sentence-order prediction (SOP) training data. To use a pretrained model, use the Hugging Face example at the end.
"""

class AlbertLikeEncoder(nn.Module):
  def __init__(self, vocab_size=30000, E=128, H=768, L=12, max_len=512, dropout=0.0):
    super().__init__()
    # Factorized embeddings: V x E embedding + E x H fully connected layer (BERT uses a single V x H embedding)
    self.tok = nn.Embedding(vocab_size, E)
    self.pos = nn.Embedding(max_len, E)
    self.seg = nn.Embedding(2, E)                    # sentence A / sentence B
    self.norm = nn.LayerNorm(E)
    self.proj = nn.Linear(E, H)
    # Cross-layer parameter sharing: create only one encoder layer and pass through it L times
    self.layer = nn.TransformerEncoderLayer(
      d_model=H, nhead=H // 64, dim_feedforward=4 * H,
      dropout=dropout, activation="gelu", batch_first=True)   # the paper's final model uses no dropout
    self.L = L
    self.sop_head = nn.Linear(H, 2)                  # predicts whether the order is correct from the [CLS] output
    self.mlm_head = nn.Linear(H, vocab_size)

  def forward(self, ids, seg_ids, pad_mask=None):
    pos = torch.arange(ids.size(1), device=ids.device)
    x = self.norm(self.tok(ids) + self.pos(pos) + self.seg(seg_ids))
    x = self.proj(x)                                 # [batch, n, E] → [batch, n, H]
    for _ in range(self.L):
      x = self.layer(x, src_key_padding_mask=pad_mask)   # use the same weights L times
    return self.mlm_head(x), self.sop_head(x[:, 0])

model = AlbertLikeEncoder()
n_params = sum(p.numel() for p in model.parameters())
print(f"Parameters: {n_params / 1e6:.1f}M")         # unchanged no matter how many times the layer is repeated

model.train()                                        # if dropout is added, it is active only during training
ids = torch.randint(5, 30000, (2, 16))
seg_ids = torch.zeros_like(ids)
mlm_logits, sop_logits = model(ids, seg_ids)
print(mlm_logits.shape, sop_logits.shape)            # [2, 16, 30000] [2, 2]

# --- Sentence-order prediction (SOP) data: two consecutive segments from the same document, swapped half the time ---
def make_sop_example(seg_a, seg_b):
  if random.random() < 0.5:
    return seg_a, seg_b, 1                           # positive: A → B
  return seg_b, seg_a, 0                             # negative: B → A (no different document, unlike NSP)

print(make_sop_example("The cat sat on the mat.", "Then it fell asleep."))

# --- Using a pretrained ALBERT (Hugging Face transformers) ---
from transformers import AutoTokenizer, AlbertForMaskedLM

name = "albert-base-v2"
tokenizer = AutoTokenizer.from_pretrained(name)      # SentencePiece (vocabulary of 30,000)
mlm = AlbertForMaskedLM.from_pretrained(name)
print(mlm.config.embedding_size, mlm.config.hidden_size)   # E = 128, H = 768
mlm.eval()
inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt")
with torch.no_grad():
  logits = mlm(**inputs).logits
mask_index = (inputs["input_ids"][0] == tokenizer.mask_token_id).nonzero(as_tuple=True)[0]
print(tokenizer.convert_ids_to_tokens(logits[0, mask_index].topk(5, dim=-1).indices[0].tolist()))

FAQ

Q. Is ALBERT faster than BERT?
A.

Because it has fewer parameters, training throughput is higher at the same shape (ALBERT-large is about 1.7 times as fast as BERT-Large). However, computation is still performed for every layer even with shared weights, so inference computation hardly decreases. The most accurate model, ALBERT-xxlarge, trains about 3 times slower than BERT-Large.

Q. Why does performance hold up when every layer uses the same weights?
A.

Even when the same processing is applied repeatedly, the input changes from layer to layer, so each layer's output is different. Still, results are lower than without sharing (average 81.6 → 80.1 with the ALBERT-base shape). ALBERT spends the saved parameters on the layer width HH, which lets it surpass BERT-Large in accuracy overall.

Q. What is the difference between sentence-order prediction (SOP) and next sentence prediction (NSP)?
A.

In both, positive examples are two consecutive segments A → B from the same document. The negatives differ: NSP pairs a segment from a different document, while SOP swaps the order of the same two segments. NSP can be solved from topic differences alone, but SOP cannot be solved without understanding how sentences connect. In the paper, switching to SOP improved results on tasks involving multiple sentences, such as SQuAD and RACE.

References

  1. Lan, Z., Chen, M., Goodman, S., Gimpel, K., Sharma, P., & Soricut, R. (2020). ALBERT: A Lite BERT for Self-supervised Learning of Language Representations. ICLR 2020. arXiv:1909.11942.
  2. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. arXiv:1810.04805.
  3. Joshi, M., Chen, D., Liu, Y., Weld, D. S., Zettlemoyer, L., & Levy, O. (2020). SpanBERT: Improving Pre-training by Representing and Predicting Spans. TACL. arXiv:1907.10529.
  4. Google Research. ALBERT (official implementation and pretrained models).
  5. Hugging Face. Transformers documentation: ALBERT.