Paper commentary
Generating Long Sequences with Sparse Transformers
- Problem Dense self-attention cost grows quadratically with sequence length, which keeps autoregressive models of images, text and raw audio from reaching long contexts.
- Method Splits each attention layer into several sparse heads whose chained paths still connect every earlier position to every later one, cutting the cost to O(n p√n). Adds a deeper residual block, recomputation of attention in the backward pass and block-sparse kernels.
- Results Reached 2.80 bits per dim on CIFAR-10 and 0.99 bits per byte on EnWik8, against 1.03 for a similarly sized Transformer-XL.
Why dense attention stalls on long sequences
Autoregressive models of images, text and audio work on sequences of discrete tokens, usually raw bytes, and output a softmax distribution over the next token. They factor the joint probability into a product of conditionals, so the likelihood of a sequence is \(p(x)=\prod_{i=1}^{n} p(x_i \mid x_1,\dots,x_{i-1};\theta)\), and training raises the log-probability of the data.
These conditionals contain long-range dependencies, so the architecture has to be expressive enough to capture them.
A Transformer handles this through self-attention, where every layer has a global receptive field, so the network can direct its capacity to the input regions that matter for a given output. The price is cost: the memory and computation of dense self-attention grow quadratically with sequence length, which rules out long sequences. Each position needs weightings over the positions before it, so the work for n positions scales with n squared.
Convolutional models such as WaveNet reach long ranges through dilation, which needs only a logarithmic number of layers for a given range. Even so, convolutional stacks still need considerable depth to widen their receptive field, which motivates an attention-based alternative.
What dense attention layers learn on CIFAR-10
Before designing a sparse pattern, the authors examined a 128-layer dense-attention network trained on CIFAR-10. Figure 2 shows early layers with locally connected patterns that resemble convolution, layers 19 and 20 splitting attention between row and column, some layers with global and data-dependent access, and typical layers from 64 to 128 that are highly sparse.
Most layers were sparse across most inputs, which suggests that some sparsity could be imposed without hurting performance much. The global and data-dependent layers would be disrupted by any predetermined pattern, so the study restricts itself to sparse patterns that connect all positions across several steps. Such patterns cannot reproduce every mapping that dense layers learn, so the experiments test whether they still perform well.
Factorized self-attention as connected steps
In self-attention, output position i is a weighted sum of value vectors over a chosen set \(S_i\) of input positions, and dense autoregressive attention takes every \(j\le i\). The keys and values are projections of the inputs at the positions in the set, and the softmax weights come from scaled query-key products. \[ a(x_i,S_i)=\mathrm{softmax}\left(\frac{(W_q x_i)K_{S_i}^{T}}{\sqrt{d}}\right)V_{S_i},\quad K_{S_i}=(W_k x_j)_{j\in S_i},\quad V_{S_i}=(W_v x_j)_{j\in S_i} \]
Factorized attention replaces that single set with \(p\) heads, each using its own subset \(A^{(m)}_i\subset\{j:j\le i\}\) as \(S_i\). The subsets are sized proportional to \(p\sqrt{n}\), which brings the cost of the layer down to \(O(n p\sqrt{n})\).
The subsets must also satisfy a path condition: for any earlier \(j\) and later \(i\), there is an index chain \((j,a,b,\dots,i)\) of length at most \(p+1\), where each hop uses the next head in order. With such chains a signal can travel from any input position to any output position in a constant number of steps, even though each layer is sparse.
Strided and fixed patterns for two-dimensional data
The work explores two factorizations with \(p=2\), and the same techniques extend to higher dimensions. Strided attention gives one head the previous \(l\) positions and the other head every \(l\)-th position, with \(l\) chosen close to \(\sqrt{n}\). \[ A^{(1)}_i=\{t,t+1,\dots,i\},\ t=\max(0,i-l),\qquad A^{(2)}_i=\{j:(i-j)\bmod l=0\} \] The authors expect this pattern to fit data whose structure lines up with the stride, such as images or some music.
For text, which has no periodic structure, the authors found the network could fail to route information through the strided pattern. The EnWik8 results show the strided pattern doing worse than dense attention on text.
Fixed attention lets some positions summarize earlier blocks: one head reads every position in the same block of width \(l\), and the other reads the last \(c\) positions of each block. \[ A^{(1)}_i=\{j:\lfloor j/l\rfloor=\lfloor i/l\rfloor\},\qquad A^{(2)}_i=\{j: j \bmod l\in\{t,\dots,l\},\ t=l-c\} \] With stride 128 and \(c=8\), positions beyond 128 attend to positions 120 to 128, positions beyond 256 attend to 248 to 256, and so on.
The choice of \(c\) trades expressivity against cost: a value of \(c=1\) is expected to limit the network significantly, because many representations are used by a single block while a few locations serve all blocks. The authors found that \(c\in\{8,16,32\}\) with \(l\in\{128,256\}\) performed well, though the cost of this method is larger than strided attention by a factor of \(c\).
With several heads, giving each head a distinct subblock of length \(c\) within the block of size \(l\) worked better than having them share one subblock.
Turning factorized heads into layers
The simplest option uses one attention pattern per residual block and interleaves the patterns sequentially or at a ratio set as a hyperparameter. \[ \mathrm{attention}(X)=W_p\,\mathrm{attend}(X,A^{(r \bmod p)}) \] Here \(r\) is the index of the residual block and \(p\) is the number of factorized heads. A merged head attends to the union of the subsets instead, which costs a constant factor more.
\[ \mathrm{attention}(X)=W_p\,\mathrm{attend}\Big(X,\bigcup_{m=1}^{p}A^{(m)}\Big) \]
Multi-head attention computes \(n_h\) attention products in parallel and concatenates them along the feature dimension. For very long sequences where attention dominates run time, the authors prefer computing the heads one at a time.
Because the layers do not know position on their own, the model adds learned embeddings that encode either the structure of the data or the factorized pattern. Each input location receives learned embeddings, one per coordinate, and their number \(n_{emb}\) equals \(d_{data}\) or \(d_{attn}\). \[ \mathrm{embed}(X,W_e)=\Big\{x_iW_e+\sum_{j=1}^{n_{emb}}o^{(j)}_iW_j\Big\}_{x_i\in X} \] Here \(x_i\) is the one-hot encoded element and \(o^{(j)}_i\) is its one-hot position in the \(j\)th dimension.
For images \(d_{data}=3\) covers the row, column and channel of each byte, while text and audio use \(d_{attn}=2\) with row and column indices in a matrix whose width is the stride.
A residual stack that trains at depth
The authors found Transformers difficult to train with many layers and chose to change the block design rather than add auxiliary losses. The network uses pre-activation residual blocks, so the final state is the input embedding plus a sum of block contributions. \[ a(H)=\mathrm{dropout}(\mathrm{attention}(\mathrm{norm}(H))),\quad b(H)=\mathrm{dropout}(\mathrm{ff}(\mathrm{norm}(H+a(H)))),\quad \mathrm{resblock}(H)=a(H)+b(H) \]
Because the final state is a sum over blocks, every block gets a direct gradient path from the output. Dropout is not applied inside the attention blocks; it is applied only at the end of each residual addition.
Memory savings from recomputation and sparse kernels
Gradient checkpointing stores only selected tensors and recomputes the attention and feed-forward blocks during the backward pass. The authors note that this is especially effective for self-attention over long sequences, because attention memory is high relative to the cost of computing it. Recomputation alone allows dense attention networks with hundreds of layers on sequences of 16,384, which the authors say would otherwise be infeasible on modern hardware.
The sparse masks are computed by slicing sub-blocks out of the query, key and value matrices and multiplying them block by block. A local window is computed directly, a stride of \(k\) is handled by transposing the matrix and applying a local window, and fixed positions are aggregated block by block.
Weights are kept in single precision, while activations and gradients are computed in half precision, which uses Tensor Core operations on the V100 GPU. Dynamic loss scaling reduces numerical underflow, half-precision gradients are communicated across GPUs, and queries and keys are cast to single precision during sampling because their product can overflow.
Optimizer, schedule and initialization
Training uses the Adam optimizer with a linear warmup over 5000 iterations, gradient clipping at 1.0 and a weight decay penalty of 0.01. The learning rate follows a cosine decay, and models train on 8 V100 GPUs unless otherwise noted. The authors found warmup and clipping important for model stability.
The embedding dimension \(d\) is usually one of 256, 512 or 1024, and most linear transforms keep dimension \(d\), with the feed-forward network projecting to \(4d\). Sometimes the query and key transformations are halved, and half-size variants use \(2d\) for the feed-forward network.
Token and position embeddings are drawn from normal distributions scaled by 0.125 and the embedding dimension, biases start at zero, and weights are scaled by the fan-in. The weight matrix for the output logits is initialized to zero.
CIFAR-10 density results
Strided Sparse Transformers were trained on CIFAR-10 images as 3072-byte sequences, with 2 heads, 128 layers and \(d=256\), plus half-size feed-forward and query-key projections. Training ran for 120 epochs at learning rate 0.00035 and dropout 0.25 until validation error stopped decreasing, using 48000 training and 2000 validation examples.
On the test set the model reached 2.80 bits per dim, with 2.798±0.004 over seeds 1, 2 and 3. The previous best value of 2.85 is from PixelSNAIL, and Table 1 lists this result as the 59M strided model. Prior-work values are quoted from other papers, so they are not a matched rerun under these conditions.
In the attention-pattern comparison, the strided model reached 2.80 with a time per iteration of 0.38, dense attention reached 2.82 at 0.54, and the fixed pattern reached 2.85 at 0.47. The strided pattern therefore gave the lowest error and the shortest iteration time on this dataset. The authors suggest the sparse patterns may point to a useful inductive bias or to an optimization issue with full attention.
EnWik8 density, speed and context length
EnWik8 tests text where two-dimensional structure is weak, and the training context length of 12,288 is longer than in previous approaches. The first 90 million tokens were used for training, and the last 10 million were reserved for validation and test. The best model had 30 layers, 8 heads, \(d=512\), dropout 0.40, 80 epochs, stride 128, \(c=32\) and merged factorized heads.
The best model reached 0.99 bits per byte, with 0.992±0.001 over seeds 1, 2 and 3, below the 1.03 for a similarly sized Transformer-XL.
On EnWik8 with a 12,288 context, dense attention reached 1.00 bits per byte with Time/Iter 1.31, fixed attention 0.99 with 0.55, and strided attention 1.13 with 0.35. Strided attention was fastest but did not match dense attention on this dataset, whereas the fixed pattern recovered and surpassed it.
At evaluation the minimum context the network could use was varied by evaluating fewer tokens in parallel, on the model trained with a 12,288 context. Bits per byte fell from 0.9952 at 6,144 tokens to 0.9908 at 12,160 tokens, with the trend monotonic across the settings. The authors read this as the network effectively using long-term dependencies.
ImageNet 64x64 and classical audio scaling
The ImageNet 64x64 model has 48 layers, a strided pattern, 16 attention heads, \(d=512\) and 152 million parameters. It reached 3.44 bits per dim, or 3.437 in one run, against 3.52 for the previous result from Menick and Kalchbrenner (2018). Prior-work values in Table 1 include PixelCNN at 3.57, Parallel Multiscale at 3.7 and Glow at 3.81.
Unconditional samples at softmax temperature 1.0 come from a model with twice the layers, 300M parameters in total.
For classical music the authors do not compare directly with prior work, because the dataset processing details are unavailable. Instead they trained, at each sequence length, the largest model that fits into 16GB V100 accelerators without model parallelism.
A 152M strided model reached 1.97 bits per byte on classical music at 12 kHz, for sequences of 65,536 samples, around 5 seconds of audio. The model-size and length trade-off is shown in Table 4, and the samples are described as globally coherent over the sampled period. Sample quality degrades at greater lengths because the model's capacity is reduced.
Limitations
Strided attention reached 1.13 bits per byte on EnWik8 against 1.00 for dense attention, so its benefit on text was not shown. The fixed pattern is the one that matched text, and it was run as the 30-layer model with stride 128 and \(c=32\).
The \(c=1\) fixed variant is discussed only as an expectation of limited expressivity, and no experiment with that setting is described.
The samples are assessed visually, and the classical audio results have no direct comparison to other work.
Paper info
- Authors
- Rewon Child, Scott Gray, Alec Radford, Ilya Sutskever
- Venue
- arXiv · Preprint
- First published
- 2019-4-23
- Added
- 2026-10-20
- Updated
- 2019-4-23
- Version
- v1
- arXiv
- 1904.10509
- Category
- cs.LG · stat.ML
- Original paper terms
- arXiv non-exclusive 1.0
- What we show
- Paper info and commentary
AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.
Quote from the paper
Rewon Child, Scott Gray, Alec Radford, Ilya Sutskever (2019). Generating Long Sequences with Sparse Transformers. arXiv:1904.10509v1. https://arxiv.org/abs/1904.10509v1
BibTeX
@misc{child2019generating,
title = {{Generating Long Sequences with Sparse Transformers}},
author = {Rewon Child and Scott Gray and Alec Radford and Ilya Sutskever},
year = {2019},
eprint = {1904.10509},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1904.10509v1}
}