advanced rag-information-theory 32 min read

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 G=(V,E,A)G = (V, E, A) has one node per entity — here a company — and a weight Aij0A_{ij} \ge 0 on the edge between ii and jj 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 ki=jAijk_i = \sum_j A_{ij} for the weighted degree of node ii and 2m=ijAij2m = \sum_{ij} A_{ij} for twice the total edge weight. A partition assigns each node ii a community label cic_i. 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 {ci}\{c_i\} of a weighted graph with adjacency AA, degrees kik_i, and total weight mm is

Q  =  12mij[Aijkikj2m]δ(ci,cj),Q \;=\; \frac{1}{2m}\sum_{ij}\left[A_{ij} - \frac{k_i k_j}{2m}\right]\delta(c_i, c_j),

where δ(ci,cj)=1\delta(c_i, c_j) = 1 if ii and jj are in the same community and 00 otherwise. The term kikj/2mk_i k_j / 2m is the expected weight between ii and jj in the configuration-model null — a random graph that preserves every degree but rewires edges at random — so QQ measures the excess of within-community edge weight over chance. It satisfies Q[12,1)Q \in [-\tfrac{1}{2}, 1), with Q0Q \approx 0 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 Q=0.778Q = 0.778 — the Panel A readout — while a random relabeling of the same nodes scores 0.04-0.04. 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 QQ, and the first move is a beautiful relaxation.

The spectral relaxation

Restrict to a bipartition — two communities — and encode it with a sign vector s{±1}ns \in \{\pm 1\}^n, with si=+1s_i = +1 for group one and si=1s_i = -1 for group two. Then δ(ci,cj)=12(sisj+1)\delta(c_i, c_j) = \tfrac{1}{2}(s_i s_j + 1), and substituting into QQ something clean happens. Define the modularity matrix

Bij  =  Aijkikj2m,B=Akk2m.B_{ij} \;=\; A_{ij} - \frac{k_i k_j}{2m}, \qquad B = A - \frac{\mathbf{k}\mathbf{k}^\top}{2m}.

Every row of BB sums to zero, because jBij=kiki2m2m=0\sum_j B_{ij} = k_i - k_i \cdot \tfrac{2m}{2m} = 0. That is exactly what kills the constant 12\tfrac{1}{2} term when we substitute, leaving

Q  =  14msBs.Q \;=\; \frac{1}{4m}\, \mathbf{s}^\top B\, \mathbf{s}.

Maximizing this over s{±1}ns \in \{\pm 1\}^n is the integer problem we cannot solve directly. So we relax: allow ss to be any real vector on the sphere s2=n\lVert s \rVert^2 = n. Then QQ is a Rayleigh quotient, and the maximizer is the eigenvector of BB with the largest eigenvalue.

Theorem 1 (The spectral relaxation (Newman 2006)).

Relaxing ss from {±1}n\{\pm 1\}^n to the sphere s2=n\lVert s \rVert^2 = n, the modularity Q=14msBsQ = \tfrac{1}{4m}\,s^\top B\,s is maximized by aligning ss with the leading eigenvector u1u_1 of the modularity matrix BB — the eigenvector of largest algebraic eigenvalue λ1\lambda_1. The spectral bipartition rounds it back to a partition by si=sign(u1i)s_i = \operatorname{sign}(u_1{}_i). Moreover, if λ10\lambda_1 \le 0, no bipartition has positive modularity: the network is indivisible, and the recursion stops.

The proof is the Rayleigh-quotient argument: on the sphere, sBss^\top B s is maximized by the top eigenvector, because expanding ss in BB‘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, BB 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 λ1(B)0\lambda_1(B) \le 0 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 Q=0.42Q = 0.42), 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.

modularity Q (at this γ)
0.778
communities found
5
Q(planted sectors), γ=1
0.778
Q(random partition)
-0.043

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 1/2m1/2m 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: ncn_c cliques of size ss, 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 2m\approx \sqrt{2m} set by the total edge weight of the graph. On a ring of ncn_c cliques, once ncn_c 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 γ\gamma (Reichardt– Bornholdt) generalizes QQ to Qγ=12mij[Aijγkikj/2m]δ(ci,cj)Q_\gamma = \tfrac{1}{2m}\sum_{ij}[A_{ij} - \gamma\, k_i k_j / 2m]\, \delta(c_i, c_j) and moves the resolvable scale, but no single γ\gamma resolves structure at multiple scales.

The notebook makes the contrast concrete. On a ring of 3030 cliques of size 55, where 2m25.7\sqrt{2m} \approx 25.7 dwarfs each clique’s internal edge count, the pairs-merged partition scores Q=0.888Q = 0.888 against the natural partition’s 0.8760.876 — so the optimum merges, and Louvain (which maximizes modularity) finds only 1515 communities, not 3030. On a small ring of 66 cliques the same comparison flips, 0.7420.742 against 0.6210.621: the cliques are resolved. Panel C’s resolution view is exactly these two comparisons. Raising γ\gamma on the large ring un-merges the cliques — γ\gamma 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 γ\gamma; 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 SBM(n,{prs})\mathrm{SBM}(n, \{p_{rs}\}) partitions nn nodes into qq blocks and places an edge between node ii (block rr) and node jj (block ss) independently with probability prsp_{rs}. The symmetric two-block sparse SBM holds the block sizes equal and writes pin=cin/np_{\text{in}} = c_{\text{in}}/n within a block and pout=cout/np_{\text{out}} = c_{\text{out}}/n across blocks, so the mean degree is (cin+cout)/2(c_{\text{in}} + c_{\text{out}})/2 and stays fixed as nn \to \infty.

The affinities cinc_{\text{in}} and coutc_{\text{out}} are the signal: when cincoutc_{\text{in}} \gg c_{\text{out}} the blocks are assortative and obvious, and when cin=coutc_{\text{in}} = c_{\text{out}} 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-nn limit — if and only if

(cincout)2  >  2(cin+cout),(c_{\text{in}} - c_{\text{out}})^2 \;>\; 2\,(c_{\text{in}} + c_{\text{out}}),

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 n=3000n = 3000 and recovers the partition from the most extreme eigenvector of the modularity matrix. Above the line, at cin=10c_{\text{in}} = 10, cout=1c_{\text{out}} = 1 (signal-to-noise 3.683.68), recovery overlaps the truth at 0.930.93. Below the line, at cin=6c_{\text{in}} = 6, cout=4c_{\text{out}} = 4 (signal-to-noise 0.200.20), recovery overlaps at 0.010.01 — 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 nn 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 11/e1 - 1/e 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, ΔQ\Delta Q 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