Ultralytics YOLO27: Join the waitlist.
License YOLO
Back to Ultralytics Glossary

Sliding Window Attention

Sliding window attention limits each token to a fixed window of recent neighbors, so attention cost and the KV cache grow linearly with length.

Sliding window attention (SWA) limits each token to attending over a fixed number of neighboring tokens, in a causal language model the w most recent ones, instead of over the whole sequence as in full self-attention. Attention compute then grows linearly with sequence length instead of quadratically, and a generating model only needs to keep the keys and values of the last w tokens in its KV cache. Longformer made the sliding window the core of its attention in 2020, and Mistral AI's Mistral 7B brought it to a widely used open large language model (LLM) in 2023, with a window of 4,096 tokens.

How the Window Grows with Depth#

One layer of SWA sees only w tokens, but transformer layers stack. At layer 2, a token reads hidden states that each already summarize w tokens from layer 1, so information can travel about w − 1 more positions with every layer, just as stacked convolutions widen the receptive field of a convolutional neural network (CNN). In PyTorch, the window is a boolean attention mask, and multiplying that mask by itself traces how far information travels:

import torch

seq_len, window = 16, 4
pos = torch.arange(seq_len)
offset = pos[:, None] - pos[None, :]

# Causal sliding window: each token attends to itself and the window - 1 tokens before it
mask = (offset >= 0) & (offset < window)
print(f"Scores per layer: {mask.sum().item()} with the window, {(offset >= 0).sum().item()} with full causal attention")

# Stacking layers widens the reach: each layer adds window - 1 more tokens of history
reach = mask
for layer in range(1, 5):
    print(f"Layer {layer}: last token draws on {reach[-1].sum().item()} tokens")
    reach = (mask.int() @ reach.int()) > 0

The window computes 58 scores per layer for 16 tokens instead of 136, and the last token's reach grows by 3 tokens per layer, from 4 to 7, 10, and 13. The same mask can be passed as attn_mask to PyTorch's scaled_dot_product_attention. For Mistral 7B, 32 layers with a 4,096-token window give a theoretical attention span of about 131K tokens, although information from far back has to survive many hops to arrive.

Mistral 7B also stores its keys and values in a rolling buffer of w slots, writing position i into slot i mod w and overwriting the oldest entry. On a 32K-token sequence, this cut cache memory eight times without hurting quality, and the fixed cache size keeps memory flat however long generation runs.

Interleaving Local and Global Layers#

Pure windows cannot copy a fact from far back in one step, so recent models mix SWA layers with full global layers. Google's Gemma 2 alternated them one to one with a 4,096-token window, and Gemma 3 uses five local layers for every global layer with a window of only 1,024 tokens, which keeps the KV cache small across a context window of up to 128K tokens. Only the global layers store keys and values for the whole context, so five of every six layers hold just 1,024 tokens each.

Vision transformers use the same mix for high-resolution images, where every patch is a token. Meta's SAM 3, which runs in the Ultralytics package for image segmentation, attends within non-overlapping 24 × 24 windows of patches in 28 of the 32 blocks of its image encoder and globally across the full 72 × 72 patch grid of a 1,008-pixel image in blocks 7, 15, 23, and 31.

  • Swin Transformer: Splits the image into fixed, non-overlapping windows that every token in the window shares, and shifts the grid between layers so neighboring windows exchange information.
  • Sparse attention: The broader family of fixed patterns. SWA is its simplest member, and others add dilated windows, global tokens, or random links.
  • Attention sinks: The first tokens of a sequence, which absorb spare attention weight. When a window is applied at inference to a model trained with full attention, evicting them breaks generation, and StreamingLLM keeps them in the cache next to the window.
  • Deformable attention: Each query attends to a few sampling points whose offsets it learns, so the neighborhood depends on the content.
  • Flash attention: A GPU kernel for exact attention. Its implementations accept a window size, so SWA models skip the blocks outside the window entirely.

Explore solutions

Computer vision in sports

Computer vision in sports

Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery

Computer vision for aerial imagery

Transform drone and aerial imagery into real-time insights for agriculture, aquaculture, environmental monitoring, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace

Computer vision in aerospace

Bring vision AI to aerial monitoring with Ultralytics YOLO models. Power drones, aerospace workflows, environmental conservation & geospatial industries with computer vision solutions.
Learn more
Computer vision in security

Computer vision in security

Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics

Computer vision in robotics

Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics

Computer vision in logistics

Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail

Computer vision in retail

Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare

Computer vision in healthcare

Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing

Computer vision in manufacturing

Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive

Computer vision in automotive

Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture

Computer vision in agriculture

Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more
Computer vision in sports
Computer vision in sports
Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery
Computer vision for aerial imagery
Transform drone and aerial imagery into real-time insights for agriculture, aquaculture, environmental monitoring, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace
Computer vision in aerospace
Bring vision AI to aerial monitoring with Ultralytics YOLO models. Power drones, aerospace workflows, environmental conservation & geospatial industries with computer vision solutions.
Learn more
Computer vision in security
Computer vision in security
Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics
Computer vision in robotics
Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics
Computer vision in logistics
Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail
Computer vision in retail
Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare
Computer vision in healthcare
Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing
Computer vision in manufacturing
Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive
Computer vision in automotive
Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture
Computer vision in agriculture
Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more
Computer vision in sports
Computer vision in sports
Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery
Computer vision for aerial imagery
Transform drone and aerial imagery into real-time insights for agriculture, aquaculture, environmental monitoring, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace
Computer vision in aerospace
Bring vision AI to aerial monitoring with Ultralytics YOLO models. Power drones, aerospace workflows, environmental conservation & geospatial industries with computer vision solutions.
Learn more
Computer vision in security
Computer vision in security
Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics
Computer vision in robotics
Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics
Computer vision in logistics
Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail
Computer vision in retail
Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare
Computer vision in healthcare
Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing
Computer vision in manufacturing
Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive
Computer vision in automotive
Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture
Computer vision in agriculture
Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning