๐Ÿค–AI/ML

Sparse Attention

Sparse Attention

A technique that improves efficiency by applying attention computation to only part of the input. Reduces O(N^2) to O(N log N), enabling long-context processing.

๐Ÿ“– Detailed Explanation

Sparse Attention is an efficient technique that computes attention only for selected position pairs, rather than for all position pairs (N^2) as in standard Self-Attention. For a 4096-token sequence, Full Attention requires about 16.7 million (4096^2) operations, whereas Sparse Attention reduces this to about 1 million with a window size of 256, making it possible to process long documents. The name derives from the fact that most of the attention matrix is 0 (sparse).

It was studied in earnest in OpenAI's 2019 paper "Generating Long Sequences with Sparse Transformers." The O(N^2) complexity of Full Attention causes memory and computation costs to explode on long sequences. When N=8192, the attention matrix alone requires 256GB of memory (in FP32). This is also why GPT-2 was limited to 1024 tokens and BERT to 512 tokens. Sparse Attention lowers the complexity to O(N log N) or O(N sqrt(N)).

Representative patterns include Local Attention (attending only to the k surrounding tokens), Strided Attention (attending at regular intervals), and Global Attention (specific tokens connect to the entire sequence). Longformer supports up to 4096 tokens by combining Local + Global, and BigBird combines Local + Global + Random to maintain theoretical expressive power. Mistral 7B's Sliding Window Attention (4096) is also a type of efficient Sparse attention. Recently, techniques such as Ring Attention, which distributes a sequence across multiple GPUs for processing, have also emerged.

It is essential for tasks that require long context, such as long document summarization, legal contract analysis, medical record processing, and understanding entire codebases. However, it requires custom CUDA kernels, which makes implementation complex and GPU optimization difficult. Flash Attention is a complementary approach that improves efficiency through memory access pattern optimization (IO-aware) rather than algorithmic sparsity, and using the two techniques together creates synergy.

๐Ÿ’ป Code Example

import torch
import torch.nn.functional as F

def create_local_attention_mask(seq_len, window_size):
    """Local Attention: ์ฃผ๋ณ€ window_size ํ† ํฐ์—๋งŒ attend"""
    mask = torch.zeros(seq_len, seq_len)
    for i in range(seq_len):
        start = max(0, i - window_size // 2)
        end = min(seq_len, i + window_size // 2 + 1)
        mask[i, start:end] = 1
    return mask

def create_strided_attention_mask(seq_len, stride):
    """Strided Attention: stride ๊ฐ„๊ฒฉ์œผ๋กœ attend"""
    mask = torch.zeros(seq_len, seq_len)
    for i in range(seq_len):
        # ๊ฐ™์€ stride ๋ธ”๋ก ๋‚ด ์œ„์น˜๋“ค
        block_start = (i // stride) * stride
        block_end = min(block_start + stride, seq_len)
        mask[i, block_start:block_end] = 1
        # ๋ชจ๋“  stride ์œ„์น˜
        mask[i, ::stride] = 1
    return mask

def create_bigbird_mask(seq_len, window_size, num_global, num_random):
    """BigBird: Local + Global + Random"""
    mask = create_local_attention_mask(seq_len, window_size)
    # Global tokens (์ฒ˜์Œ ๋ช‡ ๊ฐœ ํ† ํฐ์ด ๋ชจ๋“  ์œ„์น˜์™€ ์—ฐ๊ฒฐ)
    mask[:num_global, :] = 1
    mask[:, :num_global] = 1
    # Random connections
    for i in range(seq_len):
        random_indices = torch.randperm(seq_len)[:num_random]
        mask[i, random_indices] = 1
    return mask

# ์‚ฌ์šฉ ์˜ˆ์‹œ
seq_len = 1024
window_size = 64
local_mask = create_local_attention_mask(seq_len, window_size)
print(f"Local Attention ์—ฐ๊ฒฐ ์ˆ˜: {local_mask.sum().item():,.0f}")  # ~65K
print(f"Full Attention ์—ฐ๊ฒฐ ์ˆ˜: {seq_len * seq_len:,}")  # 1,048,576

# Hugging Face Longformer ์‚ฌ์šฉ
from transformers import LongformerModel, LongformerTokenizer

tokenizer = LongformerTokenizer.from_pretrained('allenai/longformer-base-4096')
model = LongformerModel.from_pretrained('allenai/longformer-base-4096')

# ์ตœ๋Œ€ 4096 ํ† ํฐ๊นŒ์ง€ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ (BERT๋Š” 512)
text = "This is a very long document... " * 500
inputs = tokenizer(text, return_tensors='pt', max_length=4096, truncation=True)

# global_attention_mask: 1์ธ ์œ„์น˜๋Š” ๋ชจ๋“  ํ† ํฐ๊ณผ attend
global_attention_mask = torch.zeros_like(inputs['input_ids'])
global_attention_mask[:, 0] = 1  # [CLS] ํ† ํฐ๋งŒ global

outputs = model(**inputs, global_attention_mask=global_attention_mask)

# === Sliding Window Attention (Mistral ์Šคํƒ€์ผ) ===
def create_sliding_window_mask(seq_len, window_size):
    """Sliding Window: ๊ฐ ํ† ํฐ์ด ์•ž์˜ window_size ํ† ํฐ๋งŒ attend"""
    mask = torch.zeros(seq_len, seq_len)
    for i in range(seq_len):
        start = max(0, i - window_size + 1)
        mask[i, start:i+1] = 1  # causal + window
    return mask

# Mistral 7B: window_size=4096
# 128K ํ† ํฐ๋„ 4096 ์œˆ๋„์šฐ๋กœ ํšจ์œจ์  ์ฒ˜๋ฆฌ
sliding_mask = create_sliding_window_mask(8192, 4096)
print(f"Sliding Window ์—ฐ๊ฒฐ ์ˆ˜: {sliding_mask.sum().item():,.0f}")  # ~33M
print(f"Full Attention ์—ฐ๊ฒฐ ์ˆ˜: {8192 * 8192:,}")  # 67M

# === ๋ณต์žก๋„ ๋น„๊ต ===
def attention_complexity_comparison(seq_len, window_size=256, stride=256):
    """๊ฐ Sparse ํŒจํ„ด์˜ ์—ฐ์‚ฐ ํšŸ์ˆ˜ ๋น„๊ต"""
    full = seq_len * seq_len
    local = seq_len * window_size
    strided = seq_len * (window_size + seq_len // stride)
    sliding = seq_len * min(window_size, seq_len)

    print(f"์‹œํ€€์Šค ๊ธธ์ด: {seq_len:,}")
    print(f"Full Attention: {full:,} ({full/1e6:.1f}M)")
    print(f"Local Attention: {local:,} ({local/1e6:.1f}M) - {local/full*100:.1f}%")
    print(f"Strided Attention: {strided:,} ({strided/1e6:.1f}M) - {strided/full*100:.1f}%")
    print(f"Sliding Window: {sliding:,} ({sliding/1e6:.1f}M) - {sliding/full*100:.1f}%")

attention_complexity_comparison(16384, window_size=512)

# === BigBird ํŒจํ„ด (Local + Global + Random) ===
def create_bigbird_mask(seq_len, window_size=64, num_global=64, num_random=64):
    """BigBird: ์ด๋ก ์  ํ‘œํ˜„๋ ฅ์„ ์œ ์ง€ํ•˜๋ฉด์„œ ํšจ์œจ์„ฑ ํ™•๋ณด"""
    mask = torch.zeros(seq_len, seq_len)

    for i in range(seq_len):
        # Local attention (์ฃผ๋ณ€ ํ† ํฐ)
        start = max(0, i - window_size // 2)
        end = min(seq_len, i + window_size // 2)
        mask[i, start:end] = 1

        # Global attention (์ฒ˜์Œ num_global ํ† ํฐ์ด ์ „์ฒด์™€ ์—ฐ๊ฒฐ)
        if i < num_global:
            mask[i, :] = 1
            mask[:, i] = 1

        # Random attention (๋ฌด์ž‘์œ„ ์—ฐ๊ฒฐ๋กœ ์ด๋ก ์  ํ‘œํ˜„๋ ฅ ์œ ์ง€)
        random_indices = torch.randint(0, seq_len, (num_random,))
        mask[i, random_indices] = 1

    return mask

# === Ring Attention (๋ถ„์‚ฐ ์ฒ˜๋ฆฌ) ===
# ์—ฌ๋Ÿฌ GPU์— ์‹œํ€€์Šค๋ฅผ ๋ถ„์‚ฐํ•˜์—ฌ ์ฒ˜๋ฆฌ
# ๊ฐ GPU๊ฐ€ ์ž์‹ ์˜ ์ฒญํฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ „๋‹ฌ
# 1M ํ† ํฐ ์ด์ƒ์˜ ์ดˆ์žฅ๋ฌธ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ

# === ์‹ค์ œ ๋ชจ๋ธ์—์„œ์˜ ์ ์šฉ ===
# GPT-4: 128K ์ปจํ…์ŠคํŠธ (๋‚ด๋ถ€ ์ตœ์ ํ™”)
# Claude: 200K ์ปจํ…์ŠคํŠธ (Ring Attention ์ถ”์ •)
# Mistral 7B: 32K (Sliding Window 4096)
# Longformer: 4096 (Local + Global)
# BigBird: 4096 (Local + Global + Random)

# === Attention Sink ํ˜„์ƒ ===
# ์ฒซ ๋ฒˆ์งธ ํ† ํฐ์— ์–ดํ…์…˜์ด ์ง‘์ค‘๋˜๋Š” ํ˜„์ƒ
# StreamingLLM์—์„œ ๋ฐœ๊ฒฌ: ์ฒซ ํ† ํฐ์„ ์œ ์ง€ํ•˜๋ฉด ๋ฌดํ•œ ์ƒ์„ฑ ๊ฐ€๋Šฅ

# === ์„ฑ๋Šฅ ๋ฒค์น˜๋งˆํฌ ===
# ์‹œํ€€์Šค ๊ธธ์ด 16K์—์„œ:
# - Full Attention: ๋ฉ”๋ชจ๋ฆฌ OOM (A100 40GB)
# - Sparse Attention (window=512): 8GB
# - Flash Attention: 12GB (๋” ์ •ํ™•, ๋” ๋น ๋ฆ„)
# - Sparse + Flash: 6GB (์ตœ์ )

def memory_usage_comparison(seq_lengths):
    """๋‹ค์–‘ํ•œ ์–ดํ…์…˜ ๋ฐฉ์‹ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ๋น„๊ต"""
    for n in seq_lengths:
        full = n * n * 4 / 1e9  # FP32, GB
        sparse_512 = n * 512 * 4 / 1e9
        print(f"N={n}: Full={full:.1f}GB, Sparse={sparse_512:.3f}GB")

memory_usage_comparison([4096, 8192, 16384, 32768])

# === ๊ตฌํ˜„ ๋„์ „ ๊ณผ์ œ ===
# 1. ์ปค์Šคํ…€ CUDA ์ปค๋„ ํ•„์š” (PyTorch ๊ธฐ๋ณธ X)
# 2. Sparse ํŒจํ„ด์ด GPU์—์„œ ๋น„ํšจ์œจ์ ์ผ ์ˆ˜ ์žˆ์Œ
# 3. ์ปดํŒŒ์ผ๋Ÿฌ ์ตœ์ ํ™” ์–ด๋ ค์›€
# Flash Attention์ด ๋Œ€์•ˆ์œผ๋กœ ๋ถ€์ƒํ•œ ์ด์œ !

# === ์ตœ์‹  ํŠธ๋ Œ๋“œ ===
# - Linear Attention: softmax ๋Œ€์‹  ์ปค๋„ ๊ทผ์‚ฌ
# - Performer: FAVOR+ ๋ฉ”์ปค๋‹ˆ์ฆ˜
# - Linformer: ์ €๋žญํฌ ๊ทผ์‚ฌ
# ๋ชจ๋‘ O(n^2) -> O(n) ๋ชฉํ‘œ

# === Dilated Attention (LongNet) ===
# ์ง€์ˆ˜์ ์œผ๋กœ ์ฆ๊ฐ€ํ•˜๋Š” dilation์œผ๋กœ 1B ํ† ํฐ ์ฒ˜๋ฆฌ
# ๊ฐ€๊นŒ์šด ํ† ํฐ์€ dense, ๋จผ ํ† ํฐ์€ sparseํ•˜๊ฒŒ ์ฒ˜๋ฆฌ

# === ์‹ค์ „ ์ฒดํฌ๋ฆฌ์ŠคํŠธ ===
# 1. ์‹œํ€€์Šค ๊ธธ์ด๊ฐ€ 2K ์ดํ•˜๋ฉด Full Attention์œผ๋กœ ์ถฉ๋ถ„
# 2. 2K-16K: Sliding Window ๋˜๋Š” Flash Attention
# 3. 16K-100K: BigBird, Longformer + Flash Attention
# 4. 100K+: Ring Attention, LongNet ๊ณ ๋ ค
# 5. GPU ๋ฉ”๋ชจ๋ฆฌ์™€ latency ์š”๊ตฌ์‚ฌํ•ญ์— ๋งž์ถฐ ์„ ํƒ

# === ์ตœ์‹  ๋ชจ๋ธ๋ณ„ Attention ์ „๋žต ===
# | ๋ชจ๋ธ | ์ปจํ…์ŠคํŠธ | ์ „๋žต |
# |-----|---------|-----|
# | GPT-4 Turbo | 128K | ๋‚ด๋ถ€ ์ตœ์ ํ™” |
# | Claude 3 | 200K | Ring Attention |
# | Gemini 1.5 | 1M | ๋ฉ€ํ‹ฐ๋ชจ๋‹ฌ ์ตœ์ ํ™” |

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a Long-Document Processing Discussion
"Legal documents are usually 30,000 tokens, so BERT won't work. With Longformer, you can process up to 4096 tokens at once, and understanding the context is much better than splitting it into multiple chunks. That's thanks to Local + Global Attention."
๐Ÿ’ฌ In an Interview
"Sparse Attention solves the O(N^2) problem of Full Attention. Instead of computing every pair, it computes only Local (nearby), Global (key tokens), and Random connections, reducing the cost to O(N) or O(N log N). BigBird and Longformer are representative examples, and Mistral's recent Sliding Window follows the same idea."
๐Ÿ’ฌ In a Model Selection Meeting
"If you need a 128K context, you should use a Sparse Attention model or a model with Flash Attention applied. Claude and GPT-4 Turbo are optimized internally, and among open-source options, Mistral is efficient thanks to its Sliding Window."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Common Mistakes & Cautions

โŒ
Setting the window size too small

If the Local Attention window is too small, it cannot capture relationships between distant tokens. Cross-references within a document (e.g., "as mentioned earlier") may break.

โŒ
Not setting global tokens appropriately

In Longformer, if you do not set [CLS] or the question tokens as global, summarization/QA performance drops significantly. It is important to set global positions suited to the task.

โœ…
The right way

Set the local window to at least 256โ€“512, set [CLS] as global for document classification, and set all question tokens as global for QA. Combine with Flash Attention when needed to maximize efficiency.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More