The Universal Transformer (UT) is a model that passes inputs through a single Transformer layer many times with the same weights. Dehghani and colleagues at Google Brain and DeepMind proposed it in 2019 in the paper "Universal Transformers" (ICLR 2019).
The Transformer stacks a fixed number of layers (for example, six), each with its own weights. This design is easy to compute in parallel and achieved high accuracy in translation, but the paper points out the following weaknesses.
On simple tasks that RNNs such as the LSTM can solve, such as copying strings or simple logical inference, it sometimes fails to generalize to inputs longer than those seen in training.
Because the number of layers is fixed, every input receives the same amount of processing.
UT keeps the Transformer's strength of "processing all positions in parallel and connecting any two positions with a single attention step" while adopting the RNN property of "applying the same transformation repeatedly". Unlike an RNN, however, the recurrence runs not along the sequence positions but along depth. The vector at each position is rewritten little by little by the same block.
On top of this, it can add dynamic halting (Adaptive Computation Time, ACT), which lets each position decide for itself how many more times to be rewritten. In the paper, UT reduced the Transformer's average error on the bAbI question-answering benchmark from 15.2% to 0.21%, achieved the state of the art at the time on the LAMBADA language modeling task, and scored 0.9 BLEU higher than the Transformer on English-German translation (WMT14).
Architecture and computation
Like the Transformer, UT consists of an encoder that reads the input sentence and a decoder that generates the output sentence one word at a time. The difference is that the encoder and decoder are each not "a stack of layers" but "a single block passed through T times". The left side of the figure at the top of the article shows the overall flow, and the right side shows the inside of one repeated step.
For an input of length m, the encoder computes in the following order.
Turn each token into a vector of length d with an embedding, and stack them into the matrix H0∈Rm×d.
At each step t=1,2,…,T, add the "position and timestep encoding" Pt to the previous step's Ht−1.
The attention is the same scaled dot-product attention as in the Transformer, computed in k heads. The self-attention and transition function use the same weights at every step t. Where the Transformer has "six layers, each with its own weights", UT "uses one set of weights six times".
Depending on the task, the transition function is one of the following.
Fully connected transition function: two affine transformations with a single ReLU between them, the same form as the Transformer's feed-forward network. It is applied to each position separately (with the same weights).
The position and timestep encodingPt∈Rm×d is the sum of sinusoidal positional encodings computed separately for the position i and the step t (j is the index of the vector dimension).
Because the same weights are reused, the block itself cannot tell which pass it is on. Telling it the position and the step number through Pt at every pass lets it behave differently at each step.
The decoder has the same recurrent structure. After the self-attention, it adds an attention over the encoder output HT (Q comes from the decoder side, K and V from HT). As in the Transformer, during training the target sentence is shifted one position to the right and fed in, and future positions are hidden from the self-attention with a mask. Finally, a linear transformation (O∈Rd×V, where V is the vocabulary size) and a softmax are applied to the decoder's final state to produce the probabilities of the next word.
With a fixed number of steps T, UT is equivalent to a "Transformer with weights shared across all layers". Conversely, with T=1 it is a single-layer Transformer.
Dynamic halting (ACT)
Some words in a sentence have a clear meaning, while others only become clear after revisiting the context many times. UT's dynamic halting is a mechanism that lets the model itself decide, position by position, after how many passes to stop rewriting. It attaches one instance of Graves's Adaptive Computation Time (ACT) to each position.
In the implementation in the paper's appendix, each step computes the following.
From the state at each position, a fully connected layer and a Sigmoid produce a "probability of halting here" p.
For each position, the values of p from the steps so far are summed.
Positions whose sum exceeds a threshold (a hyperparameter between 0 and 1) halt at that step. At the halting step, the "remainder", 1 minus the sum, is used as the weight.
Positions that have not yet halted are rewritten by the self-attention and the transition function. The new state is a mixture of the rewritten state and the previous state, weighted by p (or the remainder at the halting step).
The states of halted positions are copied unchanged to the next step. The process ends when all positions have halted or a preset maximum number of steps is reached.
Halted positions remain available as targets of the other positions' attention. Halting only stops "rewriting that position".
On bAbI question answering, the paper confirms that the more supporting facts a task requires for its answer, the higher the average number of steps (2.3±0.8 steps for tasks needing one supporting fact, 3.1±1.1 for two, and 3.8±2.2 for three).
Why it works
The paper explains UT's strengths in the following three points.
An inductive bias for recurrence: a structure that applies the same transformation many times suits tasks that "repeat the same procedure", such as copying or addition. The paper argues that a Transformer with differently weighted stacked layers tends to learn transformations tailored to the range of lengths seen in training and struggles to generalize to longer inputs.
Depth that adapts to the input: since the weights are shared, the number of steps can be changed even after training. In the standard Transformer, the number of sequential computations is fixed by the number of layers no matter how long the input is. The paper's appendix argues that, assuming finite precision, the standard Transformer cannot be computationally universal (Turing complete), whereas UT can be if the number of steps is chosen according to the input length.
An RNN that reads memory through attention: UT can also be viewed as "a weight-shared RNN placed at every position, where each step attends to all positions of the previous step". An ordinary RNN can only use a fixed-length state vector as memory between iterations, whereas UT can refer to the whole sequence at every iteration.
As an analogy, the Transformer is a workflow where "six editors each revise the manuscript once in turn", while UT is a workflow where "a single editor revises the manuscript as many times as needed, looking at the whole of it each time". With only one editor, there is less to learn, and the difficult passages can be revised again and again.
As for dynamic halting, in the LAMBADA experiments, a UT with dynamic halting that used 8.2±2.1 steps on average outperformed UTs fixed at 8 or 9 steps. The paper suggests this may be because reducing the number of steps for some inputs acted as a kind of regularization.
Experimental results
On bAbI question answering (20 tasks), where the Transformer failed to learn well, UT greatly reduced the average error (values are error rates in %, with the number of tasks whose error exceeds 5% in parentheses; lower is better).
Model
10K, trained per task
10K, trained jointly
1K, trained per task
1K, trained jointly
Transformer
15.2 (10/20)
22.1 (12/20)
21.8 (5/20)
26.8 (14/20)
UT
0.23 (0/20)
0.47 (0/20)
5.31 (5/20)
8.50 (8/20)
UT + dynamic halting
0.21 (0/20)
0.29 (0/20)
4.55 (3/20)
7.78 (5/20)
On algorithmic tasks trained on digit sequences of length 40 and tested on sequences of length 400, UT also far outperformed the LSTM and the Transformer (fraction of sequences that were entirely correct).
In the language modeling setting of LAMBADA (reading the previous four to five sentences and predicting the last word), the test perplexity was as follows (lower is better).
Model
Test perplexity (accuracy in parentheses)
LSTM
5174 (0.0)
Transformer
7321 (0.0)
UT (fixed at 6 steps)
319 (0.17)
UT + dynamic halting
142 (0.19)
On WMT14 English-to-German translation, a UT with the fully connected transition function and no dynamic halting outperformed a Transformer with nearly the same number of parameters.
Model
BLEU
Transformer base
28.0
Weighted Transformer base
28.4
UT base
28.9
On the subject-verb agreement task, UT (especially with dynamic halting) beat the other models by a growing margin on harder sentences with more intervening distractor nouns (on sentences with five distractor nouns, UT + dynamic halting scored 0.907 against the previous best of 0.880).
Practical considerations
Weight sharing reduces the number of parameters, not the amount of computation. Repeating a step T times costs as much as a Transformer with T stacked layers. With dynamic halting, the recurrence continues until the position needing the most steps is done, so computation time varies with the input.
Dynamic halting is not always better. In the paper, it improved results on bAbI and LAMBADA but made machine translation slightly worse, so the translation results are from a UT without dynamic halting.
The threshold and the maximum number of steps must be set as hyperparameters. Positions that reach the maximum number of steps halt even if they have not exceeded the threshold.
The algorithmic-task numbers have limits. Generalization to long inputs is better than with the LSTM or the Transformer, but the whole-sequence accuracy on addition stays at 0.02. The Neural GPU, trained with a special curriculum, scores perfectly on the same tasks.
The paper's "computational universality" argument assumes that the number of steps can grow with the input length and that enough memory is available. It does not mean that a UT running a fixed number of steps can perform any computation.
The official implementation is in TensorFlow's Tensor2Tensor. PyTorch has no built-in module, so build one by calling a single layer repeatedly, as in the example below.
Comparison with other methods
Comparing related models by how they repeat layers and how they hold weights gives the following.
Computation is not reduced. Accuracy is slightly lower than without sharing
Rough guidelines for choosing are as follows.
Tasks that repeat a procedure, such as copying, reversing, or reasoning, or when generalizing to inputs longer than those in training: UT is a candidate.
Language models pretrained on large data: Transformers without weight sharing (BERT, GPT, and so on) are the mainstream today. To keep the number of parameters down, cross-layer sharing as in ALBERT is an option.
Varying the amount of computation per input: UT's dynamic halting can be used, but on some tasks such as translation it does not help, so decide by comparing it against a UT with a fixed number of steps.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
"""
A small example of the Universal Transformer encoder (Eqs. (4)-(7) of the paper).
Passes through one encoder layer T times, adding the "position and timestep encoding" P^t at every step.
With act=True, the dynamic halting (ACT) of Appendix C decides the number of steps per position.
"""
def coordinate_embedding(m, t, d, device=None):
# Eqs. (6)(7): add sinusoidal embeddings of position i and timestep t (i and t count from 1)
i = torch.arange(1, m + 1, device=device, dtype=torch.float32).unsqueeze(1) # [m, 1]
j = torch.arange(0, d, 2, device=device, dtype=torch.float32) # 2j
div = torch.pow(10000.0, j / d) # 10000^{2j/d}
tt = torch.tensor(float(t), device=device)
P = torch.zeros(m, d, device=device)
P[:, 0::2] = torch.sin(i / div) + torch.sin(tt / div)
P[:, 1::2] = torch.cos(i / div) + torch.cos(tt / div)
return P # [m, d]
class UTBlock(nn.Module):
"""Computation of one step: A^t = LN(x + MHSA(x)), H^t = LN(A^t + Transition(A^t)) (x = H^{t-1} + P^t)"""
def __init__(self, d=512, heads=8, d_ff=2048, dropout=0.1):
super().__init__()
self.attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True)
self.ln1 = nn.LayerNorm(d)
self.transition = nn.Sequential( # fully connected transition function (2 affine maps with a ReLU between)
nn.Linear(d, d_ff), nn.ReLU(), nn.Linear(d_ff, d))
self.ln2 = nn.LayerNorm(d)
self.drop = nn.Dropout(dropout)
def forward(self, x, pad_mask=None):
a, _ = self.attn(x, x, x, key_padding_mask=pad_mask, need_weights=False)
A = self.ln1(x + self.drop(a))
return self.ln2(A + self.drop(self.transition(A)))
class UniversalTransformerEncoder(nn.Module):
def __init__(self, vocab_size, d=512, heads=8, d_ff=2048, T=6, act=False, threshold=0.99, dropout=0.1):
super().__init__()
self.embed = nn.Embedding(vocab_size, d)
self.block = UTBlock(d, heads, d_ff, dropout) # only one set of weights, reused T times
self.T, self.act, self.threshold, self.d = T, act, threshold, d
if act:
self.halt = nn.Linear(d, 1) # halting probability p (fully connected layer + sigmoid)
def forward(self, ids, pad_mask=None):
h = self.embed(ids) # H^0: [batch, m, d]
m = ids.size(1)
if not self.act:
for t in range(1, self.T + 1):
h = self.block(h + coordinate_embedding(m, t, self.d, h.device), pad_mask)
return h
# dynamic halting (procedure of Appendix C). T is used as the maximum number of steps
B = ids.size(0)
halting = torch.zeros(B, m, device=h.device)
remainders = torch.zeros(B, m, device=h.device)
n_updates = torch.zeros(B, m, device=h.device)
state = h
for t in range(1, self.T + 1):
if not ((halting < self.threshold).any()):
break
x = state + coordinate_embedding(m, t, self.d, h.device)
p = torch.sigmoid(self.halt(x)).squeeze(-1) # [B, m]
still = (halting < 1.0).float()
new_halted = ((halting + p * still) > self.threshold).float() * still
still = ((halting + p * still) <= self.threshold).float() * still
halting = halting + p * still
remainders = remainders + new_halted * (1 - halting)
halting = halting + new_halted * remainders
n_updates = n_updates + still + new_halted
w = (p * still + new_halted * remainders).unsqueeze(-1) # 0: halted positions, p: continuing positions, remainder: positions halting now
transformed = self.block(x, pad_mask)
state = transformed * w + state * (1 - w) # halted positions (w=0) copy their state unchanged
self.ponder = n_updates # number of steps per position (used for the ACT ponder penalty, etc.)
return state
model = UniversalTransformerEncoder(vocab_size=1000, d=64, heads=4, d_ff=128, T=6, act=True)
model.train() # dropout is active
ids = torch.randint(0, 1000, (2, 10))
out = model(ids)
print(out.shape) # torch.Size([2, 10, 64])
model.eval() # disable dropout for inference
# the number of parameters stays the same when T changes (one block is reused)
print(sum(p.numel() for p in model.parameters()))
FAQ
Q. Is the Universal Transformer the same as a Transformer with shared layer weights?
A.
With a fixed number of steps T and no dynamic halting, they are nearly the same. The paper itself states that "a UT with a fixed number of steps is equivalent to a multi-layer Transformer with weights tied across all its layers". The differences are that a timestep encoding Pt is added at every step and that dynamic halting can vary the number of steps per position.
Q. If it has fewer parameters, does it run faster than a Transformer?
A.
No. Since the same block is repeated T times, the computation equals that of a T-layer Transformer. Only the number of parameters (storage and memory) goes down. The same holds for ALBERT.
Q. Should dynamic halting (ACT) always be used?
A.
It depends on the task. In the paper, dynamic halting improved results on bAbI question answering and LAMBADA but made machine translation slightly worse. The safe approach is to start with a UT with a fixed number of steps and choose after comparing it with dynamic halting.