Mathematical Prerequisites for Sparse and Sliding Window Attention
Building the discrete math foundations for sparse attention patterns — the triangular number formula for counting pairs, modular arithmetic for strided patterns, the pigeonhole principle for existence proofs, and set union with inclusion-exclusion for combining connectivity sets — all derived step by step with one consistent 8-house example.
The next two posts in this series derive sparse factorized attention (the Sparse Transformer) and sliding window attention (Longformer). Both papers replace the dense attention pattern with structured sparse patterns and then prove that these patterns preserve the model’s ability to route information between any two positions.
To follow those derivations, we need four tools from discrete mathematics. The triangular number formula counts the total entries in a causal attention matrix — it appears every time we need the sum . Modular arithmetic defines which positions are “aligned” at a given stride — it is the language of strided attention patterns. The pigeonhole principle proves that two-hop paths always exist in factorized attention — it turns a counting argument into an existence guarantee. And set union with its cardinality rule combines local windows with global tokens — it is how Longformer merges two attention patterns without double-counting.
We will build all four tools from a single running example and verify every formula numerically.
The Running Example
We use 8 houses on a street, numbered 0 through 7, arranged in a row. The houses are grouped into 2 blocks of 4:
We will use this setup to build every tool: counting connections between houses, determining which block a house belongs to, proving that a mail carrier can always find a relay, and combining neighborhoods.
1. The Triangular Number Formula
1.1 Motivation
Suppose every house wants to send a greeting card to every house that comes before it on the street (lower-numbered houses only). House 0 sends nothing. House 1 sends to house 0. House 2 sends to houses 0 and 1. And so on. How many greeting cards are sent in total?
This is exactly the question that arises in causal attention: position attends to all positions , and we want the total number of attention entries.
1.2 Counting directly
Let be the number of cards house sends. Since house sends to all houses plus itself (the self-connection in attention), we have :
| House | Recipients | |
|---|---|---|
| 0 | 1 | |
| 1 | 2 | |
| 2 | 3 | |
| 3 | 4 | |
| 4 | 5 | |
| 5 | 6 | |
| 6 | 7 | |
| 7 | 8 |
The total is:
But we want a formula that works for any , not just . We want a closed form for:
1.3 Derivation: Gauss’s pairing trick
Write the sum forwards and backwards and add them:
Add the two rows term by term. Each column sums to :
There are such pairs, so:
Divide both sides by 2:
This is the triangular number formula, also called Gauss’s summation formula. The name “triangular” comes from the fact that counts the number of dots in a triangle with rows.
1.4 Numerical check
For :
We computed directly. Both sides match.
1.5 A second useful form
In the attention blogs, we often encounter the sum starting from 0:
This is identical to — we are just re-indexing. Substituting , the sum runs from to , which is exactly . The re-indexing changes nothing.
1.6 Interpretation
The triangular number formula converts a sum that takes additions into a single multiplication and division. In the sparse attention blogs, this formula appears every time we count total entries in a causal attention matrix. For a sequence of length , full causal attention has entries — the formula makes the quadratic scaling explicit.
2. Modular Arithmetic
2.1 Motivation
In the sparse attention blog, strided attention connects position to every position such that and are separated by a multiple of the stride . The formal definition says: ” is in position ‘s strided set if .” To understand this, we need the operator.
2.2 Definition
The modulo operator returns the remainder when is divided by . Formally, for integers and :
where is the floor function (the largest integer the argument), which we derived in Mathematical Prerequisites for Mixture of Experts — Part 2.
The result is always in the set .
2.3 Concrete examples with our houses
With (block size):
| House | (block number) | (position within block) |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 2 | 0 | 2 |
| 3 | 0 | 3 |
| 4 | 1 | 0 |
| 5 | 1 | 1 |
| 6 | 1 | 2 |
| 7 | 1 | 3 |
The floor gives the block number. The mod gives the position within the block. Together they partition the house number into two pieces:
This is the Euclidean division identity: every integer can be uniquely written as where is the quotient and is the remainder, with .
2.4 Numerical check
For house 7 with :
Check: .
2.5 Residue classes
A residue class modulo is the set of all integers with the same remainder when divided by . With , there are exactly 4 residue classes:
In the 8-house street, each residue class contains exactly houses. These are exactly the houses that are connected by strided attention with stride : house 0 and house 4 are in the same residue class, so strided attention connects them. House 3 and house 7 are in the same residue class, so strided attention connects them.
2.6 Congruence
Two integers and are congruent modulo , written , if they have the same remainder:
The notation means ” divides ” — that is, is a multiple of , which is equivalent to saying .
2.7 Numerical check
Are houses 3 and 7 congruent modulo 4?
Yes: . And indeed, and — same remainder.
Are houses 2 and 5 congruent modulo 4?
No: . And indeed, while — different remainders.
2.8 The key property for strided attention
The strided connectivity set in the sparse attention blog is defined as:
Using what we just derived, means , which means . So the strided set connects position to all earlier positions in the same residue class modulo . The residue classes are exactly the columns of the image grid when equals the row width — which is why strided attention naturally attends along columns.
2.9 Spacing of residue classes
Within any residue class modulo , consecutive elements are exactly apart. The class with remainder contains the elements This is an arithmetic sequence with common difference .
In our example with : class 2 contains , with consecutive elements spaced exactly 4 apart.
This spacing property will be critical in the next section, where we prove that a relay position always exists within any interval of length .
3. The Pigeonhole Principle
3.1 Motivation
The sparse attention blog proves that any two positions can communicate through a two-hop path. The proof relies on showing that an intermediate relay position must exist. The tool that guarantees existence is the pigeonhole principle.
3.2 Definition
The pigeonhole principle (also called the Dirichlet box principle) states:
The name comes from the physical setup: if 9 pigeons fly into 8 pigeonholes, at least one hole contains at least 2 pigeons. There is no way around it — the arithmetic forces a collision.
3.3 Proof
Suppose, for contradiction, that every container holds at most 1 item. Then the total number of items is at most . But we have items. Contradiction. Therefore at least one container must hold items.
This is a proof by contradiction — we assumed the opposite of what we wanted to show and derived a false statement ( when we know ), which means our assumption was wrong.
3.4 Concrete example
Suppose 5 packages must be delivered to the 4 houses in Block 0 (houses 0, 1, 2, 3). By the pigeonhole principle, at least one house receives packages.
Verify: the only way to distribute 5 packages among 4 houses is to give each house at least 1 and have 1 left over. That leftover must go to some house, giving it 2.
3.5 The generalized pigeonhole principle
A stronger version gives a tighter bound:
Here is the ceiling function: is the smallest integer . For example, .
3.6 Proof of the generalized version
Suppose every container holds at most items. Then the total is at most . We need to show this is less than .
Since (the ceiling exceeds the value by less than 1), we have:
But this bound is not strict enough. We need the sharper fact: , which gives:
So the total is strictly less than . But we have items. Contradiction.
3.7 Numerical check
With packages and houses:
So at least one house gets packages. This matches our direct reasoning above.
3.8 Application to strided attention
The sparse attention blog uses the pigeonhole principle in the following form: “In any interval of length , there is at least one representative from each residue class modulo .”
Let us derive this. Consider an interval of consecutive integers: . This interval contains exactly integers. When we compute each of these modulo , we get remainders, each in .
We claim these remainders are all distinct. The proof: take any two integers and from the interval with . Their difference is , which satisfies . Since is strictly between 0 and , it is not divisible by . By the definition of congruence, , so they have different remainders.
Since consecutive integers produce distinct remainders out of possible values , every residue class is represented exactly once.
3.9 Numerical check
Take the interval (length ). Compute each modulo 4:
Remainders: — all four residue classes are represented.
Take the interval :
Again: — all four residue classes represented.
3.10 Interpretation
This is the key result that makes the path-length argument work in the sparse attention blog. The strided attention head connects positions in the same residue class modulo . The local attention head covers consecutive positions. Since any consecutive positions contain one representative from every residue class, there is always a relay point where the two heads overlap. The pigeonhole principle turns a counting fact into an existence guarantee: we do not need to search for the relay — the principle tells us it must be there.
4. Set Operations and Cardinality
4.1 Motivation
Both the sparse attention and sliding window blogs define attention patterns as sets and then combine them. The sliding window blog combines a local window set with a global token set. The sparse attention blog takes the union of two factorized patterns. To count the total entries correctly — especially when sets overlap — we need set operations and the inclusion-exclusion principle.
4.2 Basic definitions
A set is an unordered collection of distinct elements. We write sets with curly braces. For our running example:
- The neighborhood of house 3 with radius 2:
- The set of houses in Block 0:
- The set of all houses:
The cardinality of a set , written , is the number of elements it contains:
4.3 Union
The union of two sets and , written , is the set of elements that belong to or (or both):
4.4 Intersection
The intersection of two sets and , written , is the set of elements that belong to both and :
4.5 Concrete example
Let (neighborhood of house 3) and (two “global” houses). Then:
The union has 7 elements. The intersection is empty because houses 0 and 7 are not in the neighborhood of house 3. Therefore the union’s cardinality is simply the sum of the individual cardinalities: .
Now consider (neighborhood of house 5) and :
The union has 6 elements, not . The discrepancy is because house 7 appears in both sets. We counted it twice when we added the cardinalities and must subtract it once.
4.6 The inclusion-exclusion principle
The inclusion-exclusion principle gives the correct cardinality of a union:
In words: add the sizes of both sets, then subtract the overlap to avoid double-counting.
4.7 Derivation
Every element of falls into exactly one of three categories:
- In only (not in ): there are such elements
- In only (not in ): there are such elements
- In both and : there are such elements
The total is:
Simplify by collecting the terms. The first two groups contribute each, the third contributes :
This completes the derivation.
4.8 Numerical check
For and :
We computed directly, which has 6 elements.
For and :
We computed directly, which has 7 elements.
4.9 Application to Longformer
In the sliding window attention blog, each local token’s connectivity set is the union of its local window and the set of global tokens:
where is the local window and is the set of global tokens. By inclusion-exclusion:
When a global token happens to fall inside the local window, is nonzero, and the union is smaller than the naive sum . This is exactly the overlap that the sliding window blog accounts for when tracing the connectivity table: “Note that when a global token is already in the local window, the union does not add a new entry.”
4.10 Interpretation
The inclusion-exclusion principle is a bookkeeping tool: it ensures we count each position exactly once even when two connectivity patterns overlap. Without it, we would overcount the total number of attention entries by counting shared positions twice. In practice, the overlap between local windows and global tokens is small (global tokens are few relative to the window size), so the correction is minor — but the principle is what makes the counting rigorous.
Summary
All four tools were built from the same 8 houses on a street.
The triangular number formula — derived by Gauss’s pairing trick — counts the sum in closed form. In the attention blogs, this formula counts the total entries in a causal attention matrix: , making the quadratic scaling of full attention explicit. Modular arithmetic — the operator, residue classes, and congruence — partitions positions into groups that are separated by a fixed stride . In strided attention, positions in the same residue class modulo are connected: means , and the residue classes correspond exactly to columns of an image grid when equals the row width. The pigeonhole principle guarantees that any consecutive positions contain one representative from every residue class modulo , because consecutive integers produce distinct remainders. This turns the existence of a relay position in factorized attention from a search problem into a mathematical certainty. And inclusion-exclusion — — correctly counts the entries when local windows and global tokens overlap, preventing double-counting.
With these tools in hand, we are ready for Why Full Attention Is Wasteful, where we derive sparse factorized attention patterns and prove that two-hop paths always exist, and Sliding Window Attention, where we combine local windows with global attention and count every entry precisely.
Previous: DeepSeek-V2 from Scratch: Multi-head Latent Attention and DeepSeekMoE Next: Why Full Attention Is Wasteful: Sparse Factorization from Scratch
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.