Long Context  · July 2023

LongNet — Dilated Attention

advanced

long-contextefficiency

Cover very long sequences via dilated attention — multiple attention heads operating at exponentially-increasing stride patterns, so the receptive field grows multiplicatively in depth and head count rather than linearly in either.

§ 1 · Premise

Quadratic attention versus billion-token sequences

Dense self-attention’s compute scales as O(N2d)O(N^2 d) in sequence length NN and model dim dd. At N=106N = 10^6, d=4096d = 4096 that is 1.610161.6 \cdot 10^{16} FLOPs per layer per head — already beyond what a single accelerator can hold the activations for; at N=109N = 10^9 the per-layer attention matrix alone is 410184 \cdot 10^{18} entries, six orders of magnitude past any plausible HBM budget. Ding et al. (arXiv 2307.02486) set the deliberately extreme target of training a Transformer at N=109N = 10^9, and the question they ask is: which existing sparse pattern actually composes to that regime?

The 2020-era sparse-attention literature offered several patterns, each with a known limitation at the billion-token scale:

LongNet’s wager is that the exponential generalization of stride-based attention — Sparse Transformer’s stride extended across a logarithmic number of dilation rates per head — is the right primitive: per-layer compute O(NlogN)O(N \cdot \log N), single-layer reachability of any past position at some resolution, and a distributed-training pattern that decomposes along the dilation axis. The contribution is the dilated-attention construction with its mixture-of-dilations softmax recombination, the proof of linear distributed scaling along the sequence dimension, and a demonstration at N=109N = 10^9 tokens.

§ 2 · Derivation

From local windows to exponentially-dilated mixture attention

Starting point — local-window attention. With window size ww and stride r=1r = 1, the per-query computation is

ot=softmax ⁣(qtK[tw:t]dh)V[tw:t],FLOPs=O(wdh).\mathbf{o}_t = \mathrm{softmax}\!\left(\frac{\mathbf{q}_t \, K_{[t-w:t]}^\top}{\sqrt{d_h}}\right) V_{[t-w:t]}, \quad \mathrm{FLOPs} = O(w \cdot d_h).

Compute per layer: O(Nwdh)O(N w d_h). Receptive field per layer: ww.

Step 1 — dilated indexing. Replace contiguous keys with a strided set. For dilation rate rr and segment size ww, the keys attended to by query tt are

Kr(t)={tr,t2r,,twr}.\mathcal{K}_r(t) = \left\{ t - r, t - 2r, \ldots, t - w \cdot r \right\}.

The query sees ww keys spaced rr apart, covering a span of wrw \cdot r positions but sampling only 1/r1/r of them. Mathematically this is gather-then-attend (§2.2, Eq. 2):

K~t(r)=K[Kr(t)],V~t(r)=V[Kr(t)],\widetilde{K}^{(r)}_t = K[\mathcal{K}_r(t)],\quad \widetilde{V}^{(r)}_t = V[\mathcal{K}_r(t)], ot(r)=softmax ⁣(qt(K~t(r))dh)V~t(r).\mathbf{o}^{(r)}_t = \mathrm{softmax}\!\left(\frac{\mathbf{q}_t \, (\widetilde{K}^{(r)}_t)^\top}{\sqrt{d_h}}\right) \widetilde{V}^{(r)}_t.

A single dilated head at rate rr has compute O(wdh)O(w d_h) per query — same as local attention — but a per-layer receptive field of wrw \cdot r.

Step 2 — segment-and-shuffle implementation. A naive gather is hardware-hostile (strided loads break GPU memory coalescing). Ding et al. instead realize dilated attention by segment-and-shuffle (§2.2, Figure 3): split the sequence into segments of length wrw \cdot r, reshape each segment as a w×rw \times r matrix, and transpose so the resulting r×wr \times w blocks naturally group together the indices a query at stride rr would attend to. Standard dense attention then runs within each shuffled segment at length ww. After attention, the inverse shuffle restores the sequence ordering. The overall pattern is mathematically equivalent to the gather formulation but executes as a sequence of contiguous-memory dense-attention kernels — fully Flash-Attention-compatible.

Step 3 — mixture of dilation rates. A single rate rr either covers too little reach (small rr) or too coarsely (large rr). LongNet mixes kk heads with geometrically-growing rates (§2.3):

{(wi,ri)}i=1k,ri=αi1, wi=w0βi1,\{(w_i, r_i)\}_{i=1}^{k},\quad r_i = \alpha^{i-1},\ w_i = w_0 \cdot \beta^{i-1},

with α>1\alpha > 1 (Ding et al. use α=2\alpha = 2) and segment sizes wiw_i that may also grow. The configuration in Table 1 is {(w,r)}={(2048,1),(4096,2),(8192,4),(16384,8),(32768,16)}\{(w, r)\} = \{(2048, 1), (4096, 2), (8192, 4), (16384, 8), (32768, 16)\} — five dilated patterns covering distances 13276816=524,2881 \to 32768 \cdot 16 = 524{,}288 positions per layer.

The mixture is not a simple sum of softmaxes — that would over-count positions that fall in multiple patterns. LongNet’s combination weighs each pattern’s softmax denominator proportionally to its participation (§2.3\S 2.3, Eq. 4):

ot=i=1kZi(t)j=1kZj(t)ot(ri),Zi(t)=jKri(t)exp ⁣(qtkj/dh).\mathbf{o}_t = \sum_{i=1}^{k} \frac{Z_i(t)}{\sum_{j=1}^{k} Z_j(t)} \, \mathbf{o}^{(r_i)}_t,\quad Z_i(t) = \sum_{j \in \mathcal{K}_{r_i}(t)} \exp\!\left( \mathbf{q}_t \cdot \mathbf{k}_j / \sqrt{d_h} \right).

The Zi(t)Z_i(t) are exactly the softmax denominators of each pattern’s local computation; the mixing weight is each pattern’s mass relative to the total. This is the standard online log-sum-exp recombination used in distributed attention, applied across dilation patterns rather than across sequence shards.

Why exponential dilations. Two reasons. First, one-layer reachability of every distance: for any distance dNd \le N, there exists a rate ri=2i1r_i = 2^{i-1} with ridwrir_i \le d \le w \cdot r_i, so some head’s window covers position tdt - d. Second, logarithmic head count to cover linear range: k=logα(N/w0)k = \lceil \log_\alpha(N / w_0) \rceil patterns cover the full sequence; for α=2\alpha = 2, N=109N = 10^9, w0=2048w_0 = 2048 that is k19k \approx 19 patterns — feasible to allocate across heads of a normal multi-head layer (Ding et al. use H=12H = 12 in their experiments, overloading some heads with multiple patterns).

Step 4 — cost accounting. Per layer, summing over patterns:

FLOPs    i=1kNwidh  =  Ndhi=1logNwi.\mathrm{FLOPs} \;\approx\; \sum_{i=1}^{k} N \cdot w_i \cdot d_h \;=\; N \cdot d_h \cdot \sum_{i=1}^{\lceil \log N \rceil} w_i.

With wi=w0w_i = w_0 constant, this is O(Nw0logNdh)O(N \cdot w_0 \cdot \log N \cdot d_h) — sub-quadratic by a factor of N/(w0logN)N / (w_0 \log N). With growing wi=w0βi1w_i = w_0 \beta^{i-1} as in Table 1, the cost becomes O(Nw0Ndh/(α1))O(N \cdot w_0 \cdot N \cdot d_h / (\alpha - 1)), which is back to quadratic when β=α\beta = \alpha. Ding et al.’s configuration uses β=2=α\beta = 2 = \alpha which formally is Θ(N2)\Theta(N^2) but with a 1/α1/\alpha leading constant; the practical scaling at the NN they study is sub-quadratic because of the tiny constant and the distributed-training shape.

Memory: each pattern’s attention matrix is N×wiN \times w_i; the maximum is the largest wi=32768w_i = 32768, giving an attention-matrix footprint of N32768N \cdot 32768 entries per head — for N=109N = 10^9 this requires sequence-parallel splitting across many accelerators, which is exactly what the distributed-training section (§3\S 3 of the paper) addresses.

Step 5 — distributed training along the dilation axis. Dilated attention’s special property is that each pattern is local within its shuffled segment (segment size wiw_i). This means the attention computation parallelises naturally along the sequence dimension: shard the sequence across PP devices, and each device runs dense attention within its own shard for the local-rate pattern, with cross-device communication only for the coarser-rate patterns. Ding et al. report near-linear scaling to P=32P = 32 devices at N=109N = 10^9 (Figure 5).

Parameter count. No new parameters introduced; dilated attention reuses standard WQ,WK,WV,WOW_Q, W_K, W_V, W_O. The only added “config” is the choice of {(wi,ri)}\{(w_i, r_i)\} per layer.

LongNet runs each attention head at a different stride r. The combined receptive field (right) covers a large portion of the sequence at O(L · log L) total cost.Single head, dilation r = 1Combined (4 heads, dilations [1, 2, 4, 8])k=0k=63k=0k=63Per-head budget: W = 4 keys per queryCombined budget: H · W = 16 keys per query (before deduplication of overlaps)Naive dense: L = 64 keys per query — 4.0× reduction
Each head attends to keys at a fixed stride r — head 0 attends locally (r = 1), head 1 skips every other key (r = 2), and so on up to r = 2^(H−1). Per head's budget is small (W keys), but the union of all heads covers the sequence at multiple resolutions. Total cost is O(L · log L) when dilations span 1..L.

§ 3 · Reference implementation

Segment-and-shuffle dilated attention in pseudocode

# q, k, v: [B, N, H, d_h]
# patterns: list of (w_i, r_i) tuples assigned to subsets of heads

def longnet_layer(q, k, v, patterns, head_assign):
    # head_assign: list of head indices per pattern
    outs, Zs = [], []
    for (w, r), heads in zip(patterns, head_assign):
        qh, kh, vh = q[..., heads, :], k[..., heads, :], v[..., heads, :]
        # Segment-and-shuffle: reshape so that stride-r positions become contiguous
        N = q.shape[1]
        # 1) Pad to multiple of w*r
        # 2) Reshape [B, N/(w*r), w*r, H', d_h] -> [B, N/(w*r), r, w, H', d_h] (transpose)
        # 3) Flatten the r dimension into the batch: [B * N/(w*r) * r, w, H', d_h]
        qs, ks, vs = segment_shuffle(qh, w, r), segment_shuffle(kh, w, r), segment_shuffle(vh, w, r)

        # Standard dense attention within each shuffled block (Flash-Attn under the hood)
        out_i, lse_i = flash_attention(qs, ks, vs, return_lse=True)  # lse = log Z_i

        # Inverse-shuffle back to [B, N, H', d_h]
        out_i = inverse_shuffle(out_i, w, r)
        lse_i = inverse_shuffle(lse_i, w, r)
        outs.append(out_i)
        Zs.append(exp(lse_i))                         # [B, N, H', 1]

    # Mixture combination across patterns (log-sum-exp recombination)
    Z_total = sum(Zs)
    o = sum(Z_i * o_i for Z_i, o_i in zip(Zs, outs)) / Z_total

    # Re-merge heads back to [B, N, H, d_h]
    return scatter_heads(o, head_assign)

The sketch elides three production concerns: (1) causal masking — dilated indices need a causal-respecting gather that drops keys with index >t> t; (2) padding handling when NN is not a multiple of wrw \cdot r; (3) the actual heads-to-patterns assignment, which Ding et al. keep as a fixed configuration per layer rather than learned.

§ 4 · Empirical evidence

What is and isn’t known

Introducing paper (Ding et al. 2023).

  1. Sub-quadratic scaling demonstrated. Trained MAGNETO Transformer backbones (Wang et al. 2022) with LongNet attention at sequence lengths 22K, 88K, 3232K, 128128K, 512512K, and 11M, reporting near-flat wall-clock per token vs. growing-quadratically wall-clock for dense attention (Figure 4). Dense attention OOMs at 3232K on their hardware; LongNet continues smoothly.
  2. Distributed scaling. The distributed implementation reaches near-linear throughput as training devices scale from 1 to 32 GPUs at fixed N=32N = 32K (Figure 5), and the paper describes (though does not benchmark at full hardware) the procedure for scaling to N=109N = 10^9 tokens.
  3. Language modeling perplexity. On the Stack (Kocetkov et al. 2022, a code corpus) and Pile (Gao et al. 2020), LongNet at N=32N = 32K trained for 300300B tokens reaches lower perplexity than dense attention at N=2N = 2K trained for the same number of tokens (Table 2, Table 3). The improvement is modest (0.05\sim 0.05 bpb on the Pile, 0.1\sim 0.1 bpb on the Stack) and is the result of the extended context, not an intrinsic property of the dilation pattern.
  4. Receptive-field ablation. Removing the larger dilation rates (keeping only r4r \le 4) degrades perplexity by 0.15\sim 0.15 bpb on long-document subsets of the Pile (Table 4), confirming that the mixture’s long-range patterns contribute beyond what the small-rr patterns alone provide.

Independent follow-up.

Sensitivity studies — what is not publicly known. The introducing paper does not study (a) how the dilated-attention model behaves on needle-in-a-haystack benchmarks like RULER (Hsieh et al. 2024) or the LongBench / NIAH lineage — the paper’s evaluation is language-modeling perplexity, not retrieval accuracy; (b) how LongNet composes with subsequent positional-encoding rescaling techniques (the paper uses xPos / MAGNETO’s positional encoding, not RoPE); (c) whether the configuration optimal at N=32N = 32K transfers to the N=109N = 10^9 regime — the billion-token result is a system demonstration, not a downstream-task evaluation. I don’t know of an independent reproduction at >1> 1B model parameters; published LongNet results sit at 125\sim 125M–2.72.7B MAGNETO scales.

Production adoption. None recorded in this knowledge base. No frontier dense or MoE production decoder ships pure dilated attention as its long-context primitive — the production-frontier choice in the 32K–1M regime has converged on interleaved SWA + global attention (Gemma 3, Mistral) with positional-encoding rescaling on top (YaRN, NTK-aware extension). LongNet’s specific value is asymptotic: at the billion-token regime where logN\log N heads materially outperform N\sqrt{N} patterns; that regime is not yet the production frontier.

Lineage

Cite

BibTeX entry for the original paper
@article{arxiv2307_02486,
  title  = {LongNet: Scaling Transformers to 1,000,000,000 Tokens},
  author = {Jiayu Ding and others (Microsoft Research)},
  year   = {2023},
  eprint = {2307.02486},
  archivePrefix = {arXiv},
  url    = {https://arxiv.org/abs/2307.02486}
}

Or cite the paper directly: arXiv:2307.02486.

Export

BibTeX
@article{arxiv_2307_02486,
  title         = {LongNet: Scaling Transformers to 1,000,000,000 Tokens},
  author        = {Jiayu Ding et al. (Microsoft Research)},
  year          = {2023},
  eprint        = {2307.02486},
  archivePrefix = {arXiv},
  url           = {https://arxiv.org/abs/2307.02486}
}
CSL JSON
{
  "id": "arxiv_2307_02486",
  "type": "article-journal",
  "title": "LongNet: Scaling Transformers to 1,000,000,000 Tokens",
  "author": [
    {
      "literal": "Jiayu Ding et al. (Microsoft Research)"
    }
  ],
  "issued": {
    "date-parts": [
      [
        2023
      ]
    ]
  },
  "URL": "https://arxiv.org/abs/2307.02486",
  "number": "2307.02486",
  "source": "arXiv"
}
RIS
TY  - JOUR
TI  - LongNet: Scaling Transformers to 1,000,000,000 Tokens
AU  - Jiayu Ding et al. (Microsoft Research)
PY  - 2023
JO  - arXiv
AN  - arXiv:2307.02486
UR  - https://arxiv.org/abs/2307.02486
ER  -