Put a token outside the sliding window
Build a causal window mask, sum the attention weights that escape it, and catch an operation count that flatters the saving.
Sliding-window attention lets a token attend only to itself and the previous
window - 1 tokens. Positions outside that band are masked before softmax, so
their weights are exactly zero, not merely small. A stack of such layers extends
the receptive field, but one layer cannot see beyond the window.
This example uses 16 positions and a window of 4. The mask is causal and
banded: token i may attend to j only when j <= i and i - j < 4. The
reported outside_weight_sum is zero, which is the correctness check. The
operation counts need care: full_ops counts the entire 16 x 16 matrix,
including the upper triangle that causal attention already masks, while
sliding_ops counts only the band. Comparing those two overstates the saving.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch22/sliding_window.py --seq-len 16 --window 4 --jsonPython 3.11 or later with PyTorch. CPU-only, seeded, no model download, network, GPU or credentials. It finishes in about a second.
Implementation
sliding_mask marks a position allowed only when it is not in the future and is
within the window. sliding_attention fills masked scores with negative
infinity, softmaxes, and multiplies by values. The demo recomputes the weights
and sums every weight at a masked position.
def sliding_mask(seq_len: int, window: int) -> torch.Tensor:
if window < 1:
raise ValueError("window must be positive")
mask = torch.ones(seq_len, seq_len, dtype=torch.bool)
for i in range(seq_len):
for j in range(seq_len):
if j > i or i - j >= window:
mask[i, j] = False
return mask
def sliding_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, window: int) -> torch.Tensor:
# q,k,v: [seq, d_head] or [batch, heads, seq, d_head]
d_head = q.shape[-1]
seq = q.shape[-2] if q.dim() == 4 else q.shape[0]
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_head)
mask = sliding_mask(seq, window)
# broadcast mask
while mask.dim() < scores.dim():
mask = mask.unsqueeze(0)
scores = scores.masked_fill(~mask, float("-inf"))
weights = torch.softmax(scores, dim=-1)
return torch.matmul(weights, v)
def run(seq_len: int = 16, window: int = 4, d_head: int = 8, seed: int = 0) -> SlidingResult:
torch.manual_seed(seed)
q = torch.randn(seq_len, d_head)
k = torch.randn(seq_len, d_head)
v = torch.randn(seq_len, d_head)
out = sliding_attention(q, k, v, window)
# Compute attention weights to check outside window.
scores = torch.matmul(q, k.T) / math.sqrt(d_head)
mask = sliding_mask(seq_len, window)
scores = scores.masked_fill(~mask, float("-inf"))
weights = torch.softmax(scores, dim=-1)
# Sum weights for positions outside window across all queries.
outside = 0.0
for i in range(seq_len):
for j in range(seq_len):
if not mask[i, j]:
outside += float(weights[i, j].item())
full_ops = seq_len * seq_len * d_head * 2
sliding_ops = sum(min(window, i + 1) for i in range(seq_len)) * d_head * 2Expected outcome
Observed with the command above (exit 0):
{
"seq_len": 16,
"window": 4,
"full_ops": 4096,
"sliding_ops": 928,
"outside_weight_sum": 0.0,
"metadata": {
"d_head": 8,
"seed": 0
}
}The masked weights sum to exactly 0.0, so no attention escaped the band. The
sliding operation count is sum(min(4, i + 1)) * 8 * 2 = 58 * 16 = 928. The
reported full_ops is 16 * 16 * 8 * 2 = 4096, but a causal full attention
would only compute sum(i + 1) * 8 * 2 = 136 * 16 = 2176. The honest reduction
against causal full attention is 2176 / 928 = 2.34x, not 4096 / 928 = 4.41x.
Mechanism and limitations
Documented: the mask rejects a non-positive window and marks future or too-distant positions false. The attention path masks scores before softmax. The demo recomputes the weights and sums every weight at a masked position to check the band. The tests check the allowed and disallowed positions, the zero outside sum, the operation counts and JSON serialisation.
Observed: the command exited 0 with the counts above and
outside_weight_sum: 0.0. The targeted tests.test_ch22_sliding is part of the
canonical suite; no independent test count is claimed here.
Not shown: a trained model’s quality under a window, the receptive field of a
stack of layers, kernel performance, or long-context retrieval. The operation
count is a scalar model, not a timing. The full_ops field’s inclusion of the
causal upper triangle is a genuine metric trap and is why the page recomputes the
causal comparison.
Challenge this result
Set --window 16 and --window 1. For window 16, sliding_ops should equal the
causal full count 2176, while full_ops remains 4096; explain the gap. For
window 1, each token attends only to itself, so the attention output should
become a per-position projection of its own value. Verify that the
outside_weight_sum stays zero in both cases. Then state what the metric should
report to make a windowed model comparable with a causal full-attention model.
Source and verification
Canonical source:
examples/ch22/sliding_window.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch22_sliding.py
.
Chapter: Sliding-Window Attention
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it uses random tensors, not a model.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.