On this page
Imagine an AI systems archive holding 10,000 research notes, model-serving specs, and architecture records. Ask standard vector search, "What block size does PagedAttention use in our serving config?", and top-5 similarity returns the exact paragraph in milliseconds. Now ask, "What are the dominant architectural bottlenecks limiting throughput across our inference stack?" Top-5 similarity pulls five near-duplicate notes on KV-cache fragmentation and misses kernel memory bandwidth, batch scheduling, and quantization trade-offs spread across the corpus.
The previous chapter showed how query rewriting, HyDE, Self-RAG, and CRAG sharpen single-query RAG. GraphRAG upgrades the index itself.[1][2] Alongside chunk embeddings, it extracts typed entities and relationships into a property graph, clusters dense subgraphs into hierarchical communities, and summarizes those communities into reports.[3][4] That offline structure unlocks multi-hop traversals across separate documents and corpus-wide thematic synthesis.
Why small top-k vector search hits a ceiling
Vector similarity excels on local lookups whose answer sits in a handful of nearby chunks. It stalls on two other query shapes:
- Global sensemaking queries ask about patterns across thousands of documents. Near-duplicate passages crowd the top-k window, while simply raising
kinflates prompt tokens and triggers mid-context attention drops ("lost in the middle").[5] - Multi-hop entity queries link separate documents through an intermediate entity the question never named.
GraphRAG shifts clustering and summarization offline during indexing, storing four linked artifacts: source text units, extracted entities, directed relationships, and hierarchical community reports.[1]

Multi-hop retrieval and property graphs
Consider three architecture records from a model-serving knowledge base:
- Record 1842:
inference-apidepends onRedis Cachefor embedding lookups; evictions climbed alongside p95 latency during benchmark2026.06.14. - Record 2031:
Redis Cacheinus-east-1still runsOld Maxmemory Policy, whose migration waits on a client compatibility test. - Record 3155:
inference-apiexceeded its latency target twelve minutes after rollout; rolling back restored baseline latency.
Because Record 2031 never mentions inference-api or latency, lexical or narrow top-2 search fetches Records 3155 and 1842 and misses Record 2031. Adding source-cited directed edges (inference-api -[depends_on]-> Redis Cache -[uses_policy]-> Old Maxmemory Policy) lets a two-hop walk pull Record 2031 directly into context.

inference-api -> Redis Cache -> Old Maxmemory Policy recovers Record 2031 (3/3 recall).A property graph stores triples (Subject) -[Predicate]-> (Object) with typed attributes (type, description, weight, source_chunk_ids). Always identify entities by (canonical_title, canonical_type) within a workspace scope rather than title alone: Compiler:Triton (the GPU kernel DSL) and Server:Triton (the inference runtime) must never merge into one node.
Keep graph traversal distinct from Graph Neural Networks (GNNs). Standard GraphRAG walks stored edges and summarizes communities without training a neural graph model. A GNN or Message-Passing Neural Network (MPNN) learns embeddings by aggregating neighbor vectors across layers to predict node labels or missing links.[6][7] Treat any GNN-predicted edge as a hypothesis until anchored to source text.
Phase 1: Building the GraphRAG index
Microsoft's GraphRAG pipeline turns raw chunks into entities, relationships, hierarchical communities, and community reports.[3][4]
Step 1: Typed entity resolution, lineage, and local context packing

For each text unit, an LLM using structured output (or an NLP extractor in lighter variants[8]) proposes typed entities and directed edges. Entity resolution merges duplicates sharing (canonical_title, canonical_type) plus curated aliases and unions their source_chunk_ids.[1][9]
At query time, Local Search maps the question to seed entities, expands their -hop neighborhood, verifies every hop carries valid source chunks, and packs the highest-scoring entities, edges, reports, and text units into the prompt's token budget.[10] The script below resolves an ML systems graph, rejects an ambiguous untyped Triton edge, expands two hops from vLLM, and packs candidates into a 90-token budget:
from collections import defaultdict
from dataclasses import dataclass
import numpy as np
@dataclass
class Entity:
name: str
type: str
sources: list[str]
@dataclass(frozen=True)
class Edge:
src: str
src_type: str
rel: str
dst: str
dst_type: str
sources: tuple[str, ...]
@dataclass(frozen=True)
class Candidate:
label: str
score: float
tokens: int
source: str
def norm(s: str) -> str:
return " ".join(s.casefold().split())
def build_graph(entities: list[Entity], edges: list[Edge]) -> tuple[dict, dict]:
nodes: dict[tuple[str, str], Entity] = {}
by_name: dict[str, list[tuple[str, str]]] = defaultdict(list)
for e in entities:
key = (norm(e.name), norm(e.type))
if key not in nodes:
nodes[key] = Entity(e.name, e.type, sorted(set(e.sources)))
by_name[key[0]].append(key)
else:
nodes[key].sources = sorted(set(nodes[key].sources + e.sources))
def resolve(name: str, etype: str) -> tuple[str, str]:
if etype:
key = (norm(name), norm(etype))
if key in nodes:
return key
raise ValueError(f"unknown entity: {name!r} ({etype})")
matches = by_name.get(norm(name), [])
if len(matches) != 1:
raise ValueError(f"ambiguous untyped entity: {name!r} -> {matches}")
return matches[0]
adj: dict[tuple[str, str], list[tuple[tuple[str, str], str, tuple[str, ...]]]] = defaultdict(list)
for ed in edges:
if not ed.sources:
raise ValueError(f"uncited edge: {ed.src} -[{ed.rel}]-> {ed.dst}")
adj[resolve(ed.src, ed.src_type)].append((resolve(ed.dst, ed.dst_type), ed.rel, ed.sources))
return nodes, dict(adj)
def expand_hops(adj: dict, seed: tuple[str, str], hops: int = 2) -> list[tuple[str, str]]:
visited, frontier = {seed}, {seed}
for _ in range(hops):
nxt = {v for u in frontier for v, _, _ in adj.get(u, [])} | {
u for u, es in adj.items() if any(v in frontier for v, _, _ in es)
}
frontier = nxt - visited
visited |= frontier
return sorted(visited)
def pack_context(candidates: list[Candidate], budget: int) -> list[Candidate]:
selected, used = [], 0
for idx in np.argsort([-c.score for c in candidates]):
item = candidates[int(idx)]
if used + item.tokens <= budget:
selected.append(item)
used += item.tokens
return selected
nodes, adj = build_graph(
[
Entity("FlashAttention", "Algorithm", ["paper-dao22"]),
Entity("HBM", "Hardware", ["paper-dao22"]),
Entity("HBM", "Hardware", ["paper-kwon23"]),
Entity("PagedAttention", "Algorithm", ["paper-kwon23"]),
Entity("vLLM", "Engine", ["paper-kwon23"]),
],
[
Edge("FlashAttention", "Algorithm", "minimizes_io_to", "HBM", "Hardware", ("paper-dao22",)),
Edge("vLLM", "Engine", "implements", "PagedAttention", "Algorithm", ("paper-kwon23",)),
Edge("PagedAttention", "Algorithm", "reduces_waste_in", "HBM", "Hardware", ("paper-kwon23",)),
],
)
print("HBM sources:", nodes[("hbm", "hardware")].sources)
print("2-hop vLLM: ", [nodes[k].name for k in expand_hops(adj, ("vllm", "engine"), hops=2)])
try:
build_graph(
[Entity("Triton", "Compiler", ["p1"]), Entity("Triton", "Server", ["p2"])],
[Edge("Triton", "", "targets", "Triton", "Compiler", ("p3",))],
)
except ValueError as err:
print("rejected: ", err)
packed = pack_context(
[
Candidate("vLLM->PagedAttention", 0.98, 30, "paper-kwon23"),
Candidate("block-table KV text", 0.91, 55, "paper-kwon23"),
Candidate("serving report", 0.62, 80, "comm-serving"),
],
budget=90,
)
print("packed: ", [(c.label, c.source) for c in packed])HBM sources: ['paper-dao22', 'paper-kwon23']
2-hop vLLM: ['HBM', 'PagedAttention', 'vLLM']
rejected: ambiguous untyped entity: 'Triton' -> [('triton', 'compiler'), ('triton', 'server')]
packed: [('vLLM->PagedAttention', 'paper-kwon23'), ('block-table KV text', 'paper-kwon23')]Step 2: Community detection with the Leiden algorithm
Single-entity hops cannot summarize an entire corpus. GraphRAG projects the entity graph into an undirected weighted graph and runs hierarchical Leiden clustering.[11][12]
Older Louvain clustering moves individual nodes to maximize modularity, which can detach a bridge node and leave a community internally disconnected. Leiden adds a refinement phase before aggregation so every community remains internally connected.[11] Microsoft's GraphRAG wrapper optimizes Newman modularity (resolution ), measuring excess internal edge density over a degree-preserving random null model:[13]
Here is the adjacency matrix, and are node degrees, is the undirected edge count, and when nodes and share a community. Putting all nodes in one community yields ; isolating dense clusters raises :
from collections import defaultdict, deque
def build_adj(nodes: list[str], edges: list[tuple[str, str]]) -> dict[str, set[str]]:
adj = {n: set() for n in nodes}
for u, v in edges:
adj[u].add(v)
adj[v].add(u)
return adj
def modularity(nodes: list[str], adj: dict[str, set[str]], m: int, comm: dict[str, str]) -> float:
two_m = 2 * m
total = sum(
(1.0 if j in adj[i] else 0.0) - (len(adj[i]) * len(adj[j])) / two_m
for i in nodes for j in nodes if comm[i] == comm[j]
)
return total / two_m
def refine_connected(adj: dict[str, set[str]], comm: dict[str, str]) -> dict[str, str]:
"""Ensure every community is internally connected (Leiden connectivity invariant)."""
by_comm: dict[str, set[str]] = defaultdict(set)
for node, cid in comm.items():
by_comm[cid].add(node)
refined: dict[str, str] = {}
for cid, members in by_comm.items():
unseen, part = set(members), 0
while unseen:
seed = min(unseen)
unseen.remove(seed)
q, label = deque([seed]), (f"{cid}_{part}" if part else cid)
while q:
cur = q.popleft()
refined[cur] = label
for nxt in adj[cur] & unseen:
unseen.remove(nxt)
q.append(nxt)
part += 1
return refined
nodes = ["FlashAttention", "Triton", "SRAM", "vLLM", "PagedAttention", "KV-Cache", "LoRA", "QLoRA", "NF4"]
edges = [
("FlashAttention", "Triton"), ("FlashAttention", "SRAM"), ("Triton", "SRAM"),
("vLLM", "PagedAttention"), ("vLLM", "KV-Cache"), ("PagedAttention", "KV-Cache"),
("LoRA", "QLoRA"), ("QLoRA", "NF4"), ("LoRA", "NF4"),
("FlashAttention", "vLLM"),
]
adj = build_adj(nodes, edges)
comm = {n: n for n in nodes}
improved = True
while improved:
improved, best_q = False, modularity(nodes, adj, len(edges), comm)
for node in nodes:
best_c = comm[node]
for cand in sorted({comm[nbr] for nbr in adj[node]}):
comm[node] = cand
q = modularity(nodes, adj, len(edges), comm)
if q > best_q + 1e-9:
best_q, best_c, improved = q, cand, True
comm[node] = best_c
refined = refine_connected(adj, comm)
groups: dict[str, list[str]] = defaultdict(list)
for node, cid in refined.items():
groups[cid].append(node)
print("all-in-one Q:", round(modularity(nodes, adj, len(edges), {n: "all" for n in nodes}), 3))
print("optimized Q: ", round(modularity(nodes, adj, len(edges), refined), 3))
for cid, members in sorted(groups.items()):
print(f"community {cid}: {sorted(members)}")all-in-one Q: -0.0
optimized Q: 0.565
community KV-Cache: ['KV-Cache', 'PagedAttention', 'vLLM']
community NF4: ['LoRA', 'NF4', 'QLoRA']
community SRAM: ['FlashAttention', 'SRAM', 'Triton']Hierarchical Leiden subdivides large communities recursively into a forest of nested themes (Level 0 holds broad communities; deeper levels hold finer sub-communities; Edge et al. report 34 Level-0 communities on their podcast corpus and 55 on their news corpus).[1][4]

Step 3: Community reports and authorization continuity
For every community, an LLM writes a structured Community Report (title, executive summary, key findings citing entity/edge IDs, and a 0-10 impact rating).[14]
Compressing dozens of chunks into one report introduces an indirect leakage hazard whenever documents carry access control lists (ACLs). If one community report summarizes two all-staff notes alongside one security-only note, showing that report to a regular reader exposes the restricted fact even when chunk-level vector search filtered out the restricted chunk.
Three production patterns enforce ACL continuity: equivalence-class partitioning (separate graphs per homogeneous permission scope), query-time dynamic summarization over authorized chunks (as in LazyGraphRAG), or drop with local fallback (exclude mixed unauthorized reports and fall back to authorized local entity search). See RAG Security & Access Control for full multi-tenant ACL design.
Why can community reports leak restricted data even when vector chunk search enforces ACLs?
Answer
A precomputed report summarizes many chunks together. If any contributing chunk is restricted, handing the report to an unauthorized caller exposes that fact without ever fetching the chunk directly.
Phase 2: Global search, dynamic selection, and DRIFT
Global search answers corpus-wide questions via map-reduce over community reports at a chosen level:[1][15][16]
- Map: Pack community reports into token-budgeted batches and score each report's relevance to the question in parallel.
- Reduce: Sort rated points across all batches, drop zero-relevance items, and synthesize the highest-ranked findings.
The code below builds real TF-IDF vectors over ML-systems community reports, packs token-bounded batches, scores cosine similarity weighted by community size, and reduces the top themes:
from dataclasses import dataclass
import math
import re
import numpy as np
@dataclass(frozen=True)
class Report:
id: str
title: str
summary: str
entities: int
tokens: int
def tokenize(text: str) -> list[str]:
return re.findall(r"[a-z0-9]+", text.lower())
def tfidf(docs: list[str]) -> tuple[np.ndarray, dict[str, int], np.ndarray]:
toks = [tokenize(d) for d in docs]
vocab = {t: i for i, t in enumerate(sorted({w for d in toks for w in d}))}
df = np.zeros(len(vocab))
for d in toks:
for t in set(d):
df[vocab[t]] += 1.0
idf = np.log((1.0 + len(docs)) / (1.0 + df)) + 1.0
mat = np.zeros((len(docs), len(vocab)))
for r, d in enumerate(toks):
for t in d:
mat[r, vocab[t]] += 1.0
if d:
mat[r] = (mat[r] / len(d)) * idf
norm = float(np.linalg.norm(mat[r]))
if norm > 0:
mat[r] /= norm
return mat, vocab, idf
def global_map_reduce(query: str, reports: list[Report], batch_tokens: int = 80, top_k: int = 3) -> list[tuple[float, Report]]:
mat, vocab, idf = tfidf([f"{r.title} {r.summary}" for r in reports])
q_vec = np.zeros(len(vocab))
q_toks = tokenize(query)
for t in q_toks:
if t in vocab:
q_vec[vocab[t]] += 1.0
if q_toks and np.linalg.norm(q_vec) > 0:
q_vec = (q_vec / len(q_toks)) * idf
q_vec /= float(np.linalg.norm(q_vec))
# Pack into token-bounded batches, map similarity + log community size, then reduce.
batches, cur, used = [], [], 0
for idx, rep in enumerate(reports):
if cur and used + rep.tokens > batch_tokens:
batches.append(cur)
cur, used = [], 0
cur.append((idx, rep))
used += rep.tokens
if cur:
batches.append(cur)
mapped = []
for batch in batches:
for idx, rep in batch:
sim = float(np.dot(mat[idx], q_vec))
if sim > 0.0:
mapped.append((sim * (1.0 + 0.15 * math.log1p(rep.entities)), rep))
return sorted(mapped, key=lambda pair: pair[0], reverse=True)[:top_k]
reports = [
Report("c-kernels", "Attention Kernels", "FlashAttention tiles softmax in SRAM to cut GPU HBM memory bandwidth traffic.", 14, 38),
Report("c-serving", "Serving Engines", "vLLM uses PagedAttention block tables to eliminate KV cache memory fragmentation and raise throughput.", 19, 42),
Report("c-quant", "Weight Quantization", "AWQ and FP8 compress weights to reduce GPU memory footprint and speed up decode throughput.", 12, 36),
Report("c-align", "Preference Alignment", "DPO and RLHF optimize helpfulness and refusal boundaries using human preference pairs.", 16, 35),
]
query = "How do serving engines and kernels cut GPU memory bottlenecks to improve throughput?"
for score, rep in global_map_reduce(query, reports):
print(f"[{rep.id}] score={score:.3f} | {rep.title}: {rep.summary}")[c-serving] score=0.589 | Serving Engines: vLLM uses PagedAttention block tables to eliminate KV cache memory fragmentation and raise throughput.
[c-kernels] score=0.539 | Attention Kernels: FlashAttention tiles softmax in SRAM to cut GPU HBM memory bandwidth traffic.
[c-quant] score=0.408 | Weight Quantization: AWQ and FP8 compress weights to reduce GPU memory footprint and speed up decode throughput.Mapping every Level-1 or Level-2 report gets pricey on large graphs. Dynamic community selection rates Level-0 roots first and expands only branches clearing a relevance cutoff (cutting AP News token cost by 77% vs. static Level-1 at comparable judge ratings, while descending to Level 3 on deeper queries added 34% cost for a 58.8% comprehensiveness win rate).[17][18] Its risk is a parent false negative, where a low root score hides a relevant child:
children = {"serving": ["cache", "queue"], "eval": ["judges", "metrics"]}
def select_leaves(scores: dict[str, float], cutoff: float = 0.5) -> tuple[list[str], list[str]]:
visited, selected = [], []
def visit(node: str) -> None:
visited.append(node)
if scores[node] < cutoff:
return
kids = children.get(node, [])
if not kids:
selected.append(node)
for c in kids:
visit(c)
for root in ("serving", "eval"):
visit(root)
return visited, selected
scores = {"serving": 0.9, "eval": 0.1, "cache": 0.8, "queue": 0.7}
print("normal pass: ", select_leaves(scores))
print("parent false negative:", select_leaves({**scores, "serving": 0.2}))normal pass: (['serving', 'cache', 'queue', 'eval'], ['cache', 'queue'])
parent false negative: (['serving', 'eval'], [])DRIFT (Dynamic Reasoning and Inference with Flexible Traversal) combines both modes: it primes context with matched community reports, asks follow-up questions to close entity gaps, runs local searches for those follow-ups, and synthesizes the resulting tree.[19]
Hybrid routing, lighter variants, and failure modes
LLM extraction and report generation drive roughly 75% of standard GraphRAG indexing cost.[8][20] Keep hybrid vector/BM25 for direct lookups and choose the lightest graph variant that fits your query rate and corpus churn:
| Architecture | Indexing work | Query-time evidence | Best fit |
|---|---|---|---|
| Vector RAG | Embeddings (+ BM25) | Top-k chunks | Fast fact lookups, high-churn corpora |
| GraphRAG | LLM extraction + Leiden + reports | Basic, Local, Global, DRIFT | High-volume themes on a stable corpus |
| FastGraphRAG | NLP noun-phrase graph + LLM reports[8] | Community reports + graph | Global synthesis on a tighter budget |
| LazyGraphRAG | NLP concept graph (~0.1% cost)[21] | Budgeted relevance tests | Infrequent global queries, high churn |
| LightRAG | LLM entity/edge profiles[22] | Entity + relationship search | Incremental updates without report rebuilds |
On AP News (100 queries, 5,590 articles), low-budget LazyGraphRAG matched Global Search quality at >700x lower query cost, while a higher budget (~4% of Level-2 Global cost) beat baselines on both local and global criteria.[21] Start with Parquet tables rather than a dedicated graph database, adding Neo4j or Neptune only for live cross-service traversals.[9] Incremental updates merge new nodes cleanly, whereas deletions must remove edges supported solely by the removed document and rebuild affected reports.[23]
Watch six failure modes: stuffing 100K-token prompts (mid-context attention drops[5]); routing direct lookups to GraphRAG instead of vector/BM25; skipping typed entity resolution (FlashAttention vs. flash-attn); unconstrained noun extraction creating generic super-hubs; unbudgeted full-corpus builds (benchmark on a 1% sample first); and stale report lineage failing to invalidate summaries after edits or ACL revocations.