GraphRAG: Community Detection and the Modularity of Knowledge
Multi-hop retrieval found a path; the relation 'retrievable-from' it traced has by now drawn a graph over the whole corpus, and a global, sensemaking question — what are the dominant themes across all of these filings? — has an answer that is a property of that graph's partition, not of any document or path. This is the mathematics of the partition: modularity scores it against a degree-preserving null and the modularity matrix's leading eigenvector relaxes the optimal split; the resolution limit caps the scale modularity can see; the stochastic block model's detectability threshold says when a thematic decomposition exists to be found at all; and Louvain and Leiden are the NP-hard-forced heuristics, with Leiden's refinement guaranteeing the connected communities Louvain cannot.
From a path to a partition
Multi-hop retrieval closed on a sentence that pointed past itself. Having traced the relation “retrievable-from” from query to bridge to answer, it observed that once iterative retrieval has traversed those edges enough times, the relation has drawn a graph over the whole corpus, “and the question shifts from finding a single path to understanding that graph’s global structure — its dense communities of mutually-retrievable filings.”
This is that shift. Every topic in this layer so far has answered a local question: which documents are near this query, which subset covers it, what path reaches this answer. A global, sensemaking question is different in kind. Ask what are the dominant themes across this entire corpus of filings? and no single document holds the answer, no single retrieval surfaces it, and no path traverses to it — because the answer is not a document at all. It is a property of how the corpus partitions into communities. The object of study moves from a trajectory through the graph to the graph’s partition, and the mathematics is the mathematics of that partition: when does a good partition exist, when can we find it, and what are the fundamental limits.
This is the architecture of GraphRAG (Edge et al. 2024). Rather than retrieve passages for each query, it builds an entity–relationship graph from the corpus once, partitions it into a hierarchy of communities, summarizes each community, and answers a global query by map-reducing over those summaries — each summary producing a partial answer, the partials reduced into a whole. The community detection is the load-bearing step, and it is the one with genuine mathematics. We will make five movements precise on the same finance geometry the rest of the arc used: what scores a partition (modularity), how to find the optimal one (the spectral relaxation), what scale it cannot see (the resolution limit), when thematic structure exists to be found at all (the stochastic block model’s detectability threshold), and the heuristics that do the work in practice (Louvain and Leiden).
The entity graph and modularity
Fix the object. The entity co-occurrence graph has one node per entity — here a company — and a weight on the edge between and measuring how strongly they co-occur. We build it from the dual-encoder geometry the arc has used throughout: each company has a unit direction on the sphere, and the edge weight is the sharpened cosine between two companies, so companies in the same sector — near on the sphere — are strongly connected and companies in different sectors are nearly unlinked. The sectors are the planted communities, and the question is whether the graph’s structure reveals them.
Write for the weighted degree of node and for twice the total edge weight. A partition assigns each node a community label . We need a number that says how good a partition is, and the idea — due to Newman and Girvan — is to compare the within-community edge weight to what a degree-preserving random graph would have.
Definition 1 (Modularity).
The modularity of a partition of a weighted graph with adjacency , degrees , and total weight is
where if and are in the same community and otherwise. The term is the expected weight between and in the configuration-model null — a random graph that preserves every degree but rewires edges at random — so measures the excess of within-community edge weight over chance. It satisfies , with for a random partition.
The configuration-model null is the whole idea. A partition that simply groups high-degree nodes together collects a lot of within-community edge weight, but those nodes would be linked even at random; modularity subtracts that baseline, so it rewards only the edge weight a partition captures beyond what degrees alone explain. On the finance entity graph the planted sectors score — the Panel A readout — while a random relabeling of the same nodes scores . The structure is real, and modularity sees it.
What modularity does not hand us is the optimal partition. Searching all partitions is hopeless; we need a way to find the one that maximizes , and the first move is a beautiful relaxation.
The spectral relaxation
Restrict to a bipartition — two communities — and encode it with a sign vector , with for group one and for group two. Then , and substituting into something clean happens. Define the modularity matrix
Every row of sums to zero, because . That is exactly what kills the constant term when we substitute, leaving
Maximizing this over is the integer problem we cannot solve directly. So we relax: allow to be any real vector on the sphere . Then is a Rayleigh quotient, and the maximizer is the eigenvector of with the largest eigenvalue.
Theorem 1 (The spectral relaxation (Newman 2006)).
Relaxing from to the sphere , the modularity is maximized by aligning with the leading eigenvector of the modularity matrix — the eigenvector of largest algebraic eigenvalue . The spectral bipartition rounds it back to a partition by . Moreover, if , no bipartition has positive modularity: the network is indivisible, and the recursion stops.
The proof is the Rayleigh-quotient argument: on the sphere, is maximized by the top eigenvector, because expanding in ‘s orthonormal eigenbasis (it is real-symmetric, so the spectral theorem applies) puts all the weight on the largest eigenvalue. Two honest caveats live right here. First, is indefinite — it has negative eigenvalues — so “largest algebraic” is not “largest magnitude”; a large negative eigenvalue is the wrong one to round. Second, the rounded integer partition is not the true optimum — rounding loses the relaxation’s guarantee — and finding the true optimum is genuinely hard, which Movement 5 confronts. But the indivisibility test is exact and useful: a single clique, which has no community structure, has and is correctly reported indivisible. On a small graph of two cliques joined by one edge, the spectral sign vector matches the brute-force modularity-optimal bipartition exactly (both find ), the collapse anchor that pins the method.
This is the natural place to meet the lab. Panel A is the finance entity graph with a resolution slider; Panel B is the detectability phase diagram of Movement 4; Panel C is the resolution limit and the Louvain/Leiden contrast of Movements 3 and 5.
The 25 nodes are companies; edges are co-occurrence weights, and the 5 sectors are the planted communities. Modularity scores a partition against the degree-preserving null: the planted sectors score 0.778 against a random partition's -0.043. The resolution parameter γ tunes the scale: at low γ two sectors merge (4 communities), a broad plateau recovers the 5 sectors, and at high γ the graph fragments toward singletons (10 → 25). No single γ is canonical — the resolution limit is intrinsic, not a knob to be tuned away.
Finance entity graph on the shared dense-retrieval vMF cloud (seed 7): 25 companies in 5 sectors, edge weight = the sharpened cosine of the company directions, so the sectors are the planted communities. The SBM panel is the canonical two-block generative model that says when such structure is detectable at all; the ring-of-cliques and the Louvain/Leiden witness are dedicated toy graphs. Every modularity, overlap, label, and Q is mirrored from graphrag_community_detection.py (viz_constants()); the lab recomputes only the Kesten–Stigum parabola, the SNR, and √(2m) in closed form.
The resolution limit
Modularity has a flaw that is not a bug to be patched but a property to be understood, and it is the load-bearing caveat of the whole topic. The in the definition is a global normalization — it depends on the total size of the graph — and that couples the score of a small community to the size of the entire network. The consequence, proved by Fortunato and Barthélemy, is that modularity maximization cannot resolve communities below a scale set by the whole graph.
The cleanest witness is a ring of cliques: cliques of size , each pair of adjacent cliques joined by a single edge, arranged in a ring. Each clique is unambiguously a community. Yet for the partition that puts each clique in its own community, compare its modularity to the partition that merges adjacent cliques in pairs.
Theorem 2 (The resolution limit (Fortunato–Barthélemy 2007)).
Modularity maximization cannot resolve communities smaller than a characteristic scale set by the total edge weight of the graph. On a ring of cliques, once is large enough the pairs-merged partition has strictly higher modularity than the natural one-clique-per-community partition, so the modularity-optimal partition merges genuine communities. The resolution parameter (Reichardt– Bornholdt) generalizes to and moves the resolvable scale, but no single resolves structure at multiple scales.
The notebook makes the contrast concrete. On a ring of cliques of size , where dwarfs each clique’s internal edge count, the pairs-merged partition scores against the natural partition’s — so the optimum merges, and Louvain (which maximizes modularity) finds only communities, not . On a small ring of cliques the same comparison flips, against : the cliques are resolved. Panel C’s resolution view is exactly these two comparisons. Raising on the large ring un-merges the cliques — shrinks the resolvable scale — but at the price of fragmenting larger communities elsewhere, which is why Panel A’s slider, pushed past the plateau, shatters the sectors into singletons. There is no canonical ; the limit is intrinsic to single-scale modularity.
The stochastic block model and the detectability transition
The resolution limit asks whether modularity can find a community of a given size. The deeper question is whether the community structure is there to be found at all — and it has a sharp, surprising answer that earns this topic its place in the information-theory layer. We need a generative model of a graph with planted communities.
Definition 2 (The stochastic block model).
The stochastic block model partitions nodes into blocks and places an edge between node (block ) and node (block ) independently with probability . The symmetric two-block sparse SBM holds the block sizes equal and writes within a block and across blocks, so the mean degree is and stays fixed as .
The affinities and are the signal: when the blocks are assortative and obvious, and when the graph is plain Erdős– Rényi with no community structure at all. Between them lies a phase transition — and it is not a gradual fade.
Theorem 3 (The detectability threshold (Decelle et al. 2011; Massoulié 2014; Mossel–Neeman–Sly 2015)).
For the symmetric two-block sparse SBM, a partition correlated with the planted one is recoverable — by any algorithm, in the large- limit — if and only if
the Kesten–Stigum threshold. Below it, the planted partition leaves no signature distinguishable from an Erdős–Rényi graph of the same mean degree: no algorithm, efficient or not, recovers a partition correlated with the truth, and every method does no better than a coin flip.
Read that converse carefully, because it is the heart of the topic. It is not a statement that our particular algorithm is too weak. It is a statement that the information is not present: below the threshold, the graph that the SBM generated carries no recoverable trace of which nodes belonged together. This is the exact shape of the limit the noisy-channel topic met in Fano — an entropy lower bound below which no decoder can succeed — transposed from channel decoding to community detection. The community-detection world has a recovery threshold, and Kesten–Stigum is its converse: an information-theoretic limit on what the graph makes knowable, not a limitation of any one method.
We demonstrate it rather than reprove it (the proof is a multi-paper research program). The notebook samples SBMs on both sides of the parabola at and recovers the partition from the most extreme eigenvector of the modularity matrix. Above the line, at , (signal-to-noise ), recovery overlaps the truth at . Below the line, at , (signal-to-noise ), recovery overlaps at — chance. Panel B is this phase diagram: the Kesten–Stigum parabola drawn in closed form, the measured overlap heatmap riding its boundary, and an inset graph whose blocks line up with the truth above the line and scatter into noise below it. Two honest notes qualify the picture. At finite the transition is smeared, not the asymptotic discontinuity, so the headline is the clear above/below contrast and not the exact crossing. And the clean coincidence of the information-theoretic and the efficient-algorithm thresholds holds for two blocks; with four or more, a hard phase opens where detection is possible in principle but no known efficient algorithm achieves it. We show the two-block case and name the gap.
GraphRAG, Louvain, and Leiden
The spectral relaxation handles a bipartition and recurses; in practice the workhorses are different, and the reason is one more piece of honesty.
Theorem 4 (Modularity maximization is NP-hard (Brandes et al. 2008)).
Finding the partition of maximum modularity is NP-hard (and NP-hard to approximate within some constant). Every practical method — spectral rounding, Louvain, Leiden — is therefore a heuristic with no guarantee of reaching the global optimum.
This is the same hardness that context selection escaped by having a submodular objective with a greedy certificate. Modularity has no such structure, so its greedy heuristics carry no certificate — they are fast and good in practice, and that is all the theory promises. Louvain (Blondel et al. 2008) runs two phases, iterated. In local moving, each node is, in turn, removed from its community and rejoined to the neighboring community of greatest modularity gain — a gain available in closed form, a function of the node’s weight into the target community, the community’s total degree, and the node’s own degree. In aggregation, each community collapses to a super-node and the process repeats on the smaller graph. The aggregation preserves modularity exactly, so the recursion is sound, and it produces a hierarchy of partitions, fine to coarse — precisely the dendrogram GraphRAG summarizes at multiple levels.
Louvain has a defect that Leiden was built to fix, and it is the clean Panel C demonstration.
Proposition 1 (Louvain can leave a disconnected community; Leiden cannot).
A partition with an internally disconnected community can be a fixed point of Louvain’s local moving — no single-node move improves modularity, so Louvain, once there, cannot repair it. Leiden (Traag et al. 2019) inserts a refinement phase that re-partitions each community into internally well-connected pieces before aggregating, guaranteeing every community it returns is internally connected.
The witness is small and exact. Two triangles with no edge between them, labeled one community: it is disconnected, yet no single node wants to leave — each triangle is internally cohesive and no node is more attracted elsewhere — so it is a Louvain local optimum that local moving cannot break. Leiden’s refinement splits it into its connected pieces. Panel C’s connectivity view draws exactly this: the Louvain partition with its disconnected community flagged, beside the Leiden partition where every community is connected. The honest framing matters — run from singletons, Louvain recovers the correct partition on this graph; it is not broken generically. The guarantee is what differs, and for a knowledge graph whose communities become retrievable summaries, a community that is secretly two disconnected halves is a summary of two unrelated things.
With the heuristics in hand, the GraphRAG pipeline is now fully specified mathematically. Extract the entity graph; run Leiden to get a hierarchy of communities; summarize each community at each level; answer a global query by map-reducing over the summaries. The modularity of knowledge is literal: a corpus decomposes into themes worth summarizing exactly when its entity graph has high modularity, the resolvable scale is coarse enough to keep genuine themes intact, and — the deepest condition — the block signal clears Kesten–Stigum. Below that threshold there is no thematic decomposition to summarize, and GraphRAG has nothing to offer over flat retrieval, because the structure it would summarize is not there.
What community detection trades, in one line
Local retrieval finds a path; global sensemaking needs the partition — and the partition exists, is findable, and is summarizable exactly when modularity is high, the resolvable scale is coarse enough, and the block signal clears the Kesten–Stigum threshold. Three limits, one for each pillar: NP-hardness forces heuristics, the resolution limit caps the scale they can see, and detectability decides whether there is anything to see at all.
Connections
- multi-hop traced the relation 'retrievable-from' into a graph over the corpus and ended on exactly this shift — from finding a single path to understanding that graph's global structure, its dense communities of mutually-retrievable filings; this topic studies that partition, so a local trajectory between two documents becomes a global property of how the whole corpus clusters multi-hop-iterative-retrieval
- the entity graph's edges are co-occurrence weights built from the dual-encoder sphere geometry — companies near on the sphere co-occur, so the same learned inner products that score retrieval are what give the graph its block structure, and the sectors of that geometry are the planted communities the partition recovers dense-retrieval-dual-encoders
- the noisy-channel topic priced answer error with Fano, an entropy lower bound below which no decoder succeeds; the stochastic block model's detectability threshold is the same kind of converse for community detection — below the Kesten–Stigum line no algorithm recovers the partition, an information-theoretic limit on what the graph itself makes knowable, not a failure of any one method retriever-as-noisy-channel
- PMI measured a document's evidentiary value in bits; here the question is whether the corpus has thematic structure to measure at all — a high-modularity partition is the condition under which community summaries carry information, and below the detectability threshold there is no theme to summarize, so the bits a community summary could add collapse to zero pmi-retrieval-value
- context selection maximized a monotone submodular coverage objective with greedy; modularity maximization is its NP-hard combinatorial cousin without the submodular guarantee, so Louvain and Leiden are greedy heuristics with no 1−1/e certificate — the same tension between a clean optimization story and the hardness that forces approximation context-selection-submodular-dpp
- the capstone's production pipeline indexes a corpus for retrieval; GraphRAG is the index-time community structure layered on top — partition the entity graph offline, summarize each community, and answer global queries by map-reducing over summaries, the sensemaking complement to the capstone's local retrieve-and-rank capstone-multimodal-financial-rag
References & Further Reading
- paper Finding and evaluating community structure in networks — Newman & Girvan (2004) Introduces modularity Q as the quality function for a network partition — within-community edges against the degree-preserving null — the object this whole topic is built on; Physical Review E 69, 026113
- paper Modularity and community structure in networks — Newman (2006) The modularity matrix B = A − kkᵀ/2m and the spectral relaxation: the modularity-optimal bipartition is B's leading eigenvector, the theorem behind Movement 2; PNAS 103(23):8577–8582
- paper Fast unfolding of communities in large networks (Louvain) — Blondel, Guillaume, Lambiotte & Lefebvre (2008) The Louvain method: greedy local-moving with a closed-form modularity gain, then aggregation, iterated into a hierarchy — the workhorse heuristic of Movement 5; J. Stat. Mech. P10008
- paper From Louvain to Leiden: guaranteeing well-connected communities — Traag, Waltman & van Eck (2019) Leiden adds a refinement phase guaranteeing internally-connected communities, repairing Louvain's pathology that a community can be left disconnected — the contrast Panel C demonstrates; Scientific Reports 9:5233
- paper Resolution limit in community detection — Fortunato & Barthélemy (2007) Proves modularity cannot resolve communities below a scale ≈√(2m) set by the whole graph — the ring-of-cliques merge of Movement 3 and the load-bearing rigorFlag; PNAS 104(1):36–41
- paper Asymptotic analysis of the stochastic block model for modular networks and its algorithmic applications — Decelle, Krzakala, Moore & Zdeborová (2011) Conjectures the detectability threshold (c_in − c_out)² = 2(c_in + c_out) for the sparse two-block SBM — below it no algorithm recovers the partition — the deep payload of Movement 4; Physical Review E 84, 066106
- paper Community detection thresholds and the weak Ramanujan property — Massoulié (2014) Proves the detectability conjecture (with Mossel–Neeman–Sly): below the Kesten–Stigum threshold no estimator correlates with the planted partition — the theorem behind the SBM phase transition; STOC 2014
- paper Reconstruction and estimation in the planted partition model — Mossel, Neeman & Sly (2015) The companion proof of the two-block detectability threshold, establishing both the impossibility below and achievability above Kesten–Stigum; Probability Theory and Related Fields 162
- paper On Modularity Clustering — Brandes, Delling, Gaertler, Görke, Hoefer, Nikoloski & Wagner (2008) Proves modularity maximization is NP-hard — the reason every practical method, spectral rounding included, is a heuristic with no global-optimality guarantee; IEEE Transactions on Knowledge and Data Engineering 20(2):172–188
- paper Statistical mechanics of community detection — Reichardt & Bornholdt (2006) Introduces the resolution parameter γ generalizing modularity, the knob that moves — but does not remove — the resolution limit; Physical Review E 74, 016110
- paper From Local to Global: A Graph RAG Approach to Query-Focused Summarization — Edge, Trinh, Cheng, Bradley, Chao, Mody, Truitt & Larson (2024) The Microsoft GraphRAG system: extract an entity graph, partition it hierarchically with Leiden, summarize each community, and answer global/sensemaking queries by map-reducing over summaries — the pipeline this topic supplies the mathematics for; arXiv:2404.16130
- book Elements of Information Theory — Cover & Thomas (2006) The mutual-information and entropy framing behind the detectability threshold as an information limit, carried from the PMI and noisy-channel topics; 2nd edition, Wiley