What causes quadratic attention slowdown at 128k context length and how do Flash Attention and ring attention solve it? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

What causes quadratic attention slowdown at 128k context length and how do Flash Attention and ring attention solve it?

message-square
0
1
What causes quadratic attention slowdown at 128k context length and how do Flash Attention and ring attention solve it?
What causes quadratic attention slowdown at 128k context length and how do Flash Attention and ring attention solve it? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

Overview

Standard self-attention compares every token with every other token, which takes $O(N^2)$ compute and memory for $N$ tokens. At 128k context length, the $128{,}000 \times 128{,}000$ attention score matrix becomes huge and bottlenecks GPU memory bandwidth.

  • Why standard attention slows down: Reading and writing massive $N \times N$ score and softmax matrices to slow GPU high-bandwidth memory (HBM) stalls the fast compute cores.
  • How FlashAttention and Ring Attention fix it: FlashAttention tiles the calculation inside fast on-chip SRAM without storing the full $N \times N$ matrix, while Ring Attention splits the long sequence across multiple GPUs in a ring so single-GPU memory limits never block 128k+ contexts.

Steps

  1. Measure the $N \times N$ memory bottleneck: Notice that at $N = 131{,}072$, one attention head in FP16 needs over $32\text{ GB}$ just to store a single $N \times N$ attention matrix.
  2. Use tiled online softmax (FlashAttention): Split $Q$, $K$, and $V$ into small blocks that fit in fast GPU SRAM, compute partial softmax statistics block by block, and write only the final output back to HBM.
  3. Shard long sequences across GPUs (Ring Attention): Split the 128k sequence into chunks across $P$ GPUs, compute local $Q_i \times K_j$ tiles, and pass $K_j, V_j$ blocks around a ring while overlapping network transfers with GPU math.
  4. Combine with KV-cache optimizations at inference: Pair FlashAttention with Grouped-Query Attention (GQA) and paged KV caches so decoding stays fast at full 128k context.

Example

export interface AttentionStats {
  seqLen: number;
  numHeads: number;
  headDim: number;
  bytesPerElement: number;
  standardMatrixBytes: number;
  flashTiledBytes: number;
  ringPerGpuMatrixBytes: number;
}

/**
 * Estimates memory traffic for standard attention vs. FlashAttention and Ring Attention.
 */
export function estimateAttentionMemory(params: {
  seqLen: number;
  numHeads: number;
  headDim: number;
  tileSize: number;
  numGpus: number;
  bytesPerElement?: number;
}): AttentionStats {
  const bytes = params.bytesPerElement ?? 2; // FP16 / BF16 = 2 bytes

  // Standard attention materializes full [numHeads, seqLen, seqLen] score + prob matrices
  const standardMatrixBytes =
    params.numHeads * params.seqLen * params.seqLen * bytes * 2;

  // FlashAttention keeps only [numHeads, tileSize, tileSize] tiles in fast SRAM
  const flashTiledBytes =
    params.numHeads * params.tileSize * params.tileSize * bytes * 2;

  // Ring Attention shards sequence across numGpus and tiles each shard
  const shardLen = Math.ceil(params.seqLen / Math.max(1, params.numGpus));
  const ringPerGpuMatrixBytes =
    params.numHeads * Math.min(shardLen, params.tileSize) * params.tileSize * bytes * 2;

  return {
    seqLen: params.seqLen,
    numHeads: params.numHeads,
    headDim: params.headDim,
    bytesPerElement: bytes,
    standardMatrixBytes,
    flashTiledBytes,
    ringPerGpuMatrixBytes,
  };
}

/**
 * Demonstrates block-wise online softmax used inside FlashAttention and Ring Attention.
 */
export function tiledOnlineAttentionRow(
  queryRow: number[],
  keyBlocks: number[][][],
  valueBlocks: number[][][]
): number[] {
  const headDim = queryRow.length;
  const scale = 1 / Math.sqrt(headDim);

  let runningMax = -Infinity;
  let runningSum = 0;
  const output = new Array<number>(headDim).fill(0);

  for (let b = 0; b < keyBlocks.length; b++) {
    const keys = keyBlocks[b];
    const values = valueBlocks[b];

    // 1. Compute scaled dot-product scores for the current K block only
    const scores = keys.map((k) => {
      let dot = 0;
      for (let d = 0; d < headDim; d++) {
        dot += queryRow[d] * k[d];
      }
      return dot * scale;
    });

    // 2. Find block max and update global running max safely
    const blockMax = Math.max(...scores);
    const nextMax = Math.max(runningMax, blockMax);
    const prevScale = runningMax === -Infinity ? 0 : Math.exp(runningMax - nextMax);

    // 3. Rescale accumulated numerator and denominator from prior blocks
    for (let d = 0; d < headDim; d++) {
      output[d] *= prevScale;
    }
    runningSum *= prevScale;

    // 4. Accumulate current block contributions without storing full N x N matrix
    for (let i = 0; i < scores.length; i++) {
      const weight = Math.exp(scores[i] - nextMax);
      runningSum += weight;
      for (let d = 0; d < headDim; d++) {
        output[d] += weight * values[i][d];
      }
    }

    runningMax = nextMax;
  }

  return runningSum === 0 ? output : output.map((v) => v / runningSum);
}

// Example calculation at 128k (131,072) context length
const stats = estimateAttentionMemory({
  seqLen: 131_072,
  numHeads: 32,
  headDim: 128,
  tileSize: 128,
  numGpus: 8,
});

console.log(
  "Standard attention HBM matrix (GB):",
  (stats.standardMatrixBytes / 1024 ** 3).toFixed(2)
);
console.log(
  "FlashAttention SRAM tile (MB):",
  (stats.flashTiledBytes / 1024 ** 2).toFixed(2)
);

Tips

  • FlashAttention removes memory overhead, not $O(N^2)$ FLOPs: It makes 128k context fit in memory and run much faster, but total math operations still grow quadratically unless paired with sparse or sliding-window attention.
  • Use fast interconnects for Ring Attention: Ring Attention needs high-speed GPU links like NVLink or InfiniBand so K/V block transfers finish before the GPU finishes computing each tile.
  • Watch KV-cache size during inference: Even with FlashAttention, a 128k prompt builds a large KV cache, so enable FP8 KV quantization or Grouped-Query Attention in production servers.