Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

14.5 GraphRAG & Ontology

Consider an enterprise assistant asked: “Who is the CEO of the company that acquired the startup whose model we licensed?” A vector retriever may return chunks about the startup, the acquisition, and several CEOs, yet still miss the answer. Similarity ranking does not explicitly enforce that the retrieved company, acquisition, and CEO belong to the same relationship path.

This distinction is important because many real-world questions are not simply “find a similar paragraph” problems. They are entity-and-edge problems: ownership lineage, incident timelines, dependency provenance, contract relationships, or corpus-level theme discovery. A knowledge graph (KG) makes such relationships explicit. Graph-augmented retrieval can use those edges alongside text retrieval; it is an option to evaluate, not a necessary replacement for vector search.


1. When GraphRAG Is Operationally Justified

GraphRAG is operationally heavier than plain vector RAG, so it should justify its additional cost and complexity. It is most useful when the workload is dominated by:

  • multi-hop questions that require following relationships across documents
  • global summarization over a corpus, not just local passage lookup
  • provenance-sensitive workflows where you must show how an answer was assembled

If most user traffic still looks like “find the paragraph that says X,” vector RAG is usually cheaper and simpler. GraphRAG becomes attractive when edges and communities, not just chunks, determine answer quality.


2. Ontology and extraction schemas

An ontology defines entity types, relations and semantic constraints. RDF/OWL and property graphs are different representation choices; using an LLM does not eliminate schema design or governance.

An LLM can propose relations from text. Attach source document/span, extractor version, validity interval and access controls to each candidate. A schema-valid edge can still be false. Resolve entities using identifiers, time, types and source evidence, not names or embedding similarity alone; retain a reversible merge record.

3. Practical Implementation: Extracting Entities and Relationships

To build a Knowledge Graph from unstructured text, we prompt an LLM to identify entities and their relationships, returning them in a structured format (like JSON).

The following offline Python example checks the structure of an authored extraction.

Educational offline example. Validates an authored extraction structure only. It omits extraction, factual verification, authorization, validity checks and persistence.

# Authored extraction output: this example does not call an LLM.
def validate_graph(graph):
    nodes = graph["entities"]
    ids = [node["id"] for node in nodes]
    if len(ids) != len(set(ids)):
        raise ValueError("duplicate entity IDs")
    allowed_relations = {"ACQUIRED_BY", "HAS_CEO"}
    for edge in graph["relationships"]:
        if edge["source"] not in ids or edge["target"] not in ids:
            raise ValueError("edge references an unknown entity")
        if edge["type"] not in allowed_relations or not edge["source_span"]:
            raise ValueError("unsupported relation or missing evidence")
    return graph  # Structural validation, not verification of factual truth.

graph = validate_graph({
    "entities": [{"id": "Orion"}, {"id": "Northstar"}, {"id": "Mina"}],
    "relationships": [
        {"source": "Orion", "target": "Northstar", "type": "ACQUIRED_BY",
         "source_span": "Fictional memo A: Northstar acquired Orion."},
        {"source": "Northstar", "target": "Mina", "type": "HAS_CEO",
         "source_span": "Fictional memo B: Mina is Northstar's CEO."},
    ],
})
print(len(graph["relationships"]))  # 2

4. Multi-hop traversal

Suppose fictional documents say Orion was acquired by Northstar and Mina is Northstar’s CEO. Following Orion → Northstar → Mina provides candidate evidence for an answer. Validity dates and source passages still need checking, and the generator can still answer incorrectly.

The interaction contrasts retrieval paths. Vector retrieval can also find the right documents; a graph can fail because of missing or incorrect edges.

Retrieval paths and missing evidence

Authored fictional documents: A says Northstar acquired Orion; B says Mina is Northstar’s CEO. Query: who leads Orion’s acquirer?

Orion → Northstar → Mina

Two edges locate candidate evidence. Check dates, permissions and source spans before answering.

Authored teaching example; no retrieval model or graph database is running.

Engineering Graph Retrieval: Random Walk with Restart (RWR)

A schema-constrained traversal can follow a known relation such as ACQUIRED_BY. When the useful neighborhood is less obvious, Random Walk with Restart (RWR) can rank nodes by proximity to a seed distribution. This is an optional graph-retrieval mechanism, not the definition of Microsoft GraphRAG local search.

Given a starting distribution p0\mathbf{p}_0 (the initial nodes found via vector search), the algorithm simulates a random walker traversing the graph’s edges. To prevent the walker from drifting too far into irrelevant territory, it has a probability cc of “teleporting” back to the start.

pt+1=(1−c)(Wpt+p0dTpt)+cp0.\mathbf{p}_{t+1}=(1-c)(\mathbf W\mathbf p_t+\mathbf p_0\mathbf d^T\mathbf p_t)+c\mathbf p_0.

Here pt\mathbf p_t is the node-probability vector after tt steps, and 0<c≤10 < c \leq 1 is the restart probability. W\mathbf W normalizes non-dangling adjacency columns and leaves dangling columns zero. Entry djd_j is 1 for a dangling node and 0 otherwise. The mass dTpt\mathbf d^T\mathbf p_t is redistributed to the initial distribution p0\mathbf p_0. The code below implements this completed transition.

Who runs the company that acquired Orion? Add a third fictional memo to the two above. It names Vendor Z as a supplier to Northstar. The walk uses the endpoints of all three edges and leaves their relation types and source memos for the evidence check.

CPU example. Run the block with PyTorch installed. The dense VV-node matrix needs O(V2)O(V^2) storage and work per iteration. It returns dangling mass to the starting distribution and stops after 20 steps. The three memos and their extracted relations are supplied as fixtures.

import torch

class GraphRetriever:
    """
    A PyTorch implementation of Graph Retrieval using Random Walk with Restart (RWR).
    This assigns graph-proximity scores around an initial seed distribution.
    """
    def __init__(self, num_nodes: int, edges: torch.Tensor, restart_prob: float = 0.15):
        """
        Args:
            num_nodes: Total number of entities in the knowledge graph.
            edges: Tensor of shape (2, num_edges). edges[0] is source, edges[1] is target.
            restart_prob: Probability (c) of teleporting back to the initial search nodes.
        """
        if num_nodes < 1 or not 0 < restart_prob <= 1:
            raise ValueError("Require nodes > 0 and restart probability in (0, 1]")
        self.num_nodes = num_nodes
        self.restart_prob = restart_prob

        # Initialize adjacency matrix
        self.adj_matrix = torch.zeros(num_nodes, num_nodes)

        # For a column-stochastic matrix where p_{t+1} = W * p_t,
        # columns represent source nodes, rows represent target nodes.
        self.adj_matrix[edges[1], edges[0]] = 1.0

        # Normalize adjacency matrix (column-stochastic)
        out_degree = self.adj_matrix.sum(dim=0, keepdim=True)
        self.dangling = (out_degree.squeeze(0) == 0)
        out_degree = out_degree.clamp_min(1.0)
        self.trans_matrix = self.adj_matrix / out_degree

    def retrieve_subgraph(self, initial_nodes: torch.Tensor, num_steps: int = 15) -> torch.Tensor:
        """
        Args:
            initial_nodes: Tensor (num_nodes, 1) representing the starting distribution
                           (e.g., nodes found via initial vector embedding search).
        Returns:
            Relevance scores for all nodes in the graph.
        """
        # Normalize initial distribution
        if initial_nodes.shape != (self.num_nodes, 1):
            raise ValueError("Expected initial_nodes shape [num_nodes, 1]")
        if not torch.isfinite(initial_nodes).all() or (initial_nodes < 0).any() or initial_nodes.sum() <= 0:
            raise ValueError("Initial distribution must have finite nonnegative positive mass")
        p_0 = initial_nodes / initial_nodes.sum()
        p_t = p_0.clone()

        # A fixed number of power iterations; convergence is not checked.
        for _ in range(num_steps):
            dangling_mass = p_t[self.dangling].sum()
            walk = self.trans_matrix @ p_t + dangling_mass * p_0
            p_t = (1 - self.restart_prob) * walk + self.restart_prob * p_0

        return p_t


def follow(facts, candidates, subject, relation):
    return [(target, memo) for source, kind, target, memo in facts
            if source == subject and kind == relation and target in candidates]


if __name__ == "__main__":
    nodes = ["Orion", "Northstar", "Mina", "Vendor Z"]
    ids = {name: i for i, name in enumerate(nodes)}
    memos = {"A": "Northstar acquired Orion.",
             "B": "Mina is Northstar's CEO.",
             "C": "Vendor Z supplies equipment to Northstar."}
    facts = [("Orion", "ACQUIRED_BY", "Northstar", "A"),
             ("Northstar", "HAS_CEO", "Mina", "B"),
             ("Northstar", "HAS_SUPPLIER", "Vendor Z", "C")]
    edges = torch.tensor([(ids[s], ids[t]) for s, _, t, _ in facts]).T
    retriever = GraphRetriever(len(nodes), edges, restart_prob=0.2)
    initial = torch.zeros(len(nodes), 1)
    initial[ids["Orion"]] = 1.0
    scores = retriever.retrieve_subgraph(initial, num_steps=20).flatten()

    cutoff = torch.topk(scores, k=3).values[-1]
    candidates = {name for name in nodes if scores[ids[name]] >= cutoff}
    for name in sorted(candidates, key=lambda n: (-scores[ids[n]].item(), n)):
        print(f"{name}: {scores[ids[name]]:.6f}")

    for buyer, first_memo in follow(facts, candidates, "Orion", "ACQUIRED_BY"):
        for person, second_memo in follow(facts, candidates, buyer, "HAS_CEO"):
            print(f"{person} | {first_memo}: {memos[first_memo]} "
                  f"| {second_memo}: {memos[second_memo]}")

The output gives Orion 0.406056 and Northstar 0.324845. Mina and Vendor Z tie for third at 0.134550. Both receive half of Northstar’s outgoing probability and both have no outgoing edges. Asking torch.topk for three indices would return just one of them, and PyTorch does not promise which tied index it will return [7]. This example keeps everyone at or above the third score, so four candidates survive.

Now look at the last output line: Mina | A: Northstar acquired Orion. | B: Mina is Northstar's CEO. Memo A identifies the buyer. Memo B supports the CEO relation. Memo C supports a supplier relation and cannot answer the question, even though Vendor Z received the same score as Mina. If three candidates are a hard limit, use a declared tie policy and check whether it drops the supporting evidence.

HippoRAG combines extracted knowledge graphs with Personalized PageRank and reports improvements over its evaluated multi-hop baselines [3]. Those results concern the paper’s datasets and retrieval configurations. The small RWR example above does not reproduce that system or establish a cost advantage.


5. Microsoft GraphRAG: Reports Before Questions

“Who acquired Orion?” and “What recurring risks appear across these incident reports?” ask for different evidence. A relationship path may help the first. The second needs coverage across many documents; a few similar passages can miss smaller themes. Microsoft’s GraphRAG paper studies this query-focused summarization problem using an entity graph and precomputed community reports [1].

Documentation checked as of 2026-11-18. The diagram separates the reusable index from the work repeated for each global query [4] [5]. Community detection does not itself produce an answer.

Index time: prepare reusable material

  1. Source text and IDsRetain document versions and evidence spans.
  2. Extract entities and relationsBuild candidate graph records from text.
  3. Detect hierarchical communitiesGroup connected entities into clusters.
  4. Store community reportsGenerate summaries before a question arrives.

Stored reports are reused. There is no final answer yet.

Query time: answer this question

  1. Question + stored reportsBatch reports from a chosen hierarchy level within the context budget.
  2. Map: question-specific pointsGenerate candidate answer points from each report batch.
  3. Filter/rank → reduceSynthesize selected points into the final answer.
HTML/CSS schematic of global search, based on the Microsoft GraphRAG paper and official indexing/global-search documentation. It does not enumerate every search mode or implementation step. Documentation checked: 2026-11-18.

What is stored, and what is generated per question?

During indexing, extraction builds entities and relations with source links. Hierarchical community detection groups connected entities; the Leiden algorithm is one method used in this process [2]. The pipeline then generates community reports. These are stored summaries, with information already selected and compressed before any particular user question [4].

For global search, reports from a selected hierarchy level are divided into context-sized batches. Each map call uses the question and a batch to propose answer points. Filtering and ranking choose points for the reduce call, which synthesizes a final response [5]. An intermediate importance score is a selection signal, not a calibrated probability that a point is true.

This global-search path uses reports as its context. That does not mean every GraphRAG query ignores source text: the documented local-search path combines graph records and information from input documents around relevant entities [6]. Choose a retrieval path for the question rather than treating all graph methods as one algorithm.

A cost and omission example

Suppose an authored example has 120 eligible reports at one hierarchy level. If each map call can hold four complete reports, the query needs 30 map calls plus one reduce call. Suppose each map result contributes 200 tokens: the reduce stage then faces 6,000 candidate tokens before its own prompt and answer budget. If only 3,000 candidate tokens fit, some information must be filtered or compressed. These are illustrative budgets, not defaults or measured GraphRAG costs. Parallel map calls may reduce elapsed time, but they do not remove token work.

Now suppose a safety issue appears in only two source documents. It can disappear during extraction, report summarization, or selection of map results. A fluent global answer cannot establish that the issue was considered. Test corpus coverage against known facts and minority themes, and trace selected claims back through reports to source spans.

When a source changes or loses access permission, its derived graph records and reports need invalidation or regeneration before reuse. Treat the source snapshot, extraction configuration, graph, reports, and access policy as a versioned retrieval artifact. A rollout should compare answer support and coverage by query type, indexing/update cost, query cost, and latency against the simpler baseline. More graph structure is useful only when that comparison warrants its maintenance burden.

6. Practical Takeaway

A graph can supply a relationship path; a community-report hierarchy can supply broader coverage. Neither certifies its extracted facts or its generated summaries. Keep source provenance and the index/query boundary visible so that stale evidence and omissions can be diagnosed.

The next section, 14.6 RAG Failure Modes and Operational Design, follows evidence through a failed answer and tests which stage needs repair.


Quizzes

Quiz 1: Why can a few top-k passages be insufficient for global summarization? Highly relevant passages may not represent the distribution of themes. Community summaries can broaden coverage but require separate omission and distortion checks.

Quiz 2: Does LLM extraction replace schema design and validation? No. Types, entity identity, relation semantics, provenance, validity and permissions still need governance. Structurally valid output can be factually wrong.

Quiz 3: What role does Leiden community detection play before global search answers a question? It detects communities of connected entities. The indexing pipeline uses those communities to organize stored reports; the query-time map/reduce stage still has to answer the particular question. Detecting a community neither writes its report nor verifies its facts.

Quiz 4: In the provided PyTorch Random Walk with Restart (RWR) implementation, what is the role of the restart_prob parameter? Each step assigns a fraction cc of probability mass to the starting distribution and a fraction 1−c1-c to the completed graph transition. A larger restart probability gives the starting nodes more weight and limits exploration of distant nodes. Neither a high score nor frequent restarts verifies a node’s factual relevance to the question.

Quiz 5: Why is embedding similarity insufficient for entity merging? Similar names or descriptions can refer to different entities. Check identifiers, types, time and source passages, and preserve merge lineage. Define duplicate-edge and weight semantics before renormalizing transition probabilities.

Quiz 6: Why might a rare issue disappear even when the original documents remain in the index? Extraction may omit its relation, a community report may compress it away, or the query-time map/reduce budget may filter it out. Check the evidence at each boundary. Increasing the final answer length cannot restore information missing from every supplied report.


References

  1. Edge, D., et al. (2024). From Local to Global: A Graph RAG Approach to Query-Focused Summarization. arXiv:2404.16130.

  2. Traag, V. A., Waltman, L., & van Eck, N. J. (2019). From Louvain to Leiden: guaranteeing well-connected communities. Scientific Reports 9, 5233. Open manuscript.

  3. Gutiérrez, B. J., Shu, Y., Gu, Y., Yasunaga, M., & Su, Y. (2024). HippoRAG: Neurobiologically Inspired Long-Term Memory for Large Language Models. NeurIPS 2024. arXiv:2405.14831.

  4. Microsoft. GraphRAG Indexing Overview. Official documentation.

  5. Microsoft. GraphRAG Global Search. Official documentation.

  6. Microsoft. GraphRAG Local Search. Official documentation.

  7. PyTorch. torch.topk, version 2.15, note on tied indices. API documentation.