AI Logic

Architectures

Universal Transformer

Updated:

The Universal Transformer architecture. The left side shows the overall flow (a recurrent encoder block and a recurrent decoder block, each repeated T times with the same weights) and the dynamic halting mechanism; the right side shows the inside of one step (position and timestep encoding, self-attention, the attention over the encoder output that only the decoder has, the transition function, and the residual connection and layer normalization around each)

Background and overview

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 TT 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 mm, the encoder computes in the following order.

  1. Turn each token into a vector of length dd with an embedding, and stack them into the matrix H0∈Rm×dH^0 \in \mathbb{R}^{m \times d}.
  2. At each step t=1,2,…,Tt = 1, 2, \dots, T, add the "position and timestep encoding" PtP^t to the previous step's Ht−1H^{t-1}.
  3. Apply self-attention with multi-head attention to the sum, then pass it through a residual connection and layer normalization to obtain AtA^t.
  4. Apply the transition function to AtA^t position by position, then again pass it through a residual connection and layer normalization to obtain HtH^t.
  5. Repeat steps 2 to 4 TT times and use the final HTH^T as the encoder output.

Steps 3 and 4 are written as follows.

At=LayerNorm((Ht−1+Pt)+MultiHeadSelfAttention(Ht−1+Pt))A^t = \mathrm{LayerNorm}\Bigl(\bigl(H^{t-1} + P^t\bigr) + \mathrm{MultiHeadSelfAttention}\bigl(H^{t-1} + P^t\bigr)\Bigr) Ht=LayerNorm(At+Transition(At))H^t = \mathrm{LayerNorm}\bigl(A^t + \mathrm{Transition}(A^t)\bigr)

The attention is the same scaled dot-product attention as in the Transformer, computed in kk heads. The self-attention and transition function use the same weights at every step tt. 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).
  • Separable convolution: a depthwise separable convolution applied over the sequence.

The position and timestep encoding Pt∈Rm×dP^t \in \mathbb{R}^{m \times d} is the sum of sinusoidal positional encodings computed separately for the position ii and the step tt (jj is the index of the vector dimension).

Pi,2jt=sin⁡ ⁣(i100002j/d)+sin⁡ ⁣(t100002j/d),Pi,2j+1t=cos⁡ ⁣(i100002j/d)+cos⁡ ⁣(t100002j/d)P^t_{i,2j} = \sin\!\left(\frac{i}{10000^{2j/d}}\right) + \sin\!\left(\frac{t}{10000^{2j/d}}\right), \qquad P^t_{i,2j+1} = \cos\!\left(\frac{i}{10000^{2j/d}}\right) + \cos\!\left(\frac{t}{10000^{2j/d}}\right)

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 PtP^t 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 HTH^T (QQ comes from the decoder side, KK and VV from HTH^T). 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×VO \in \mathbb{R}^{d \times V}, where VV 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 TT, UT is equivalent to a "Transformer with weights shared across all layers". Conversely, with T=1T = 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.

  1. From the state at each position, a fully connected layer and a Sigmoid produce a "probability of halting here" pp.
  2. For each position, the values of pp from the steps so far are summed.
  3. 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.
  4. 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 pp (or the remainder at the halting step).
  5. 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).

Model10K, trained per task10K, trained jointly1K, trained per task1K, trained jointly
Transformer15.2 (10/20)22.1 (12/20)21.8 (5/20)26.8 (14/20)
UT0.23 (0/20)0.47 (0/20)5.31 (5/20)8.50 (8/20)
UT + dynamic halting0.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).

ModelCopyReverseAddition
LSTM0.090.110.0
Transformer0.030.060.0
UT0.350.460.02

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).

ModelTest perplexity (accuracy in parentheses)
LSTM5174 (0.0)
Transformer7321 (0.0)
UT (fixed at 6 steps)319 (0.17)
UT + dynamic halting142 (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.

ModelBLEU
Transformer base28.0
Weighted Transformer base28.4
UT base28.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 TT times costs as much as a Transformer with TT 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.

ModelDirection of recurrenceLayer weightsDepthStrengthsWeaknesses
RNNs such as the LSTMAlong sequence positionsOne set shared across all timestepsSet by the sequence lengthSuited to repetitive tasksPositions cannot be computed in parallel. Distant positions are hard to connect
TransformerNone (stacked layers)Separate for each layerFixed by the number of layersParallel computation and high accuracySometimes generalizes poorly to long inputs
Universal TransformerAlong depthOne set shared across all stepsTT is selectable; with dynamic halting it varies per positionParallel computation and strong on repetitive tasksComputation is not reduced. Dynamic halting needs tuning
ALBERTAlong depthOne set shared across all layersFixed by the number of layersGreatly reduces parametersComputation 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 TT 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 PtP^t 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 TT times, the computation equals that of a TT-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.

References

  1. Dehghani, M., Gouws, S., Vinyals, O., Uszkoreit, J., & Kaiser, Ł. (2019). Universal Transformers. ICLR 2019. arXiv:1807.03819.
  2. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. arXiv:1706.03762.
  3. Graves, A. (2016). Adaptive Computation Time for Recurrent Neural Networks. arXiv:1603.08983.
  4. Tensor2Tensor (includes the official implementation of the Universal Transformer).