CS224W

Lecture 16 · Tue 11/17 · slides PDF · lecture notes

LLMs + GNNs

LLMs are fluent but shaky at multi-hop, precise reasoning over structured facts; GNNs are small, deterministic and multi-hop by construction — so let the GNN feed the LLM (GraphRAG, G-Retriever) or the LLM feed the GNN (text-attributed graphs, GLEM).

24
sectionstick "got it" as you go
18
figuresredrawn from the slides
interactive figuresplay with the ideas
5
self-check questionsplus flashcards
18′
reading time3,944 words, walkthrough aside

Before you start: review of the earlier sessions

The thread so far. Sessions 14–15 built graph foundation models; sessions 16–17 look from the other side, at how LLMs can use graphs.

What this session takes from earlier ones

  • Lecture 8: self-attention and transformers: what an LLM is made of
  • Lecture 10: knowledge graphs, the structured side of retrieval
  • Lecture 6: what a GNN can and cannot compute, contrasted with an LLM's associative recall

Those sessions in one minute each

Lecture 15 · Towards Foundation Models for Knowledge Graphs

Transfer across knowledge graphs requires that no parameter is tied to a specific entity or relation: build a relation graph from shared heads and tails, compute relation embeddings with a GNN on it, and compute entity embeddings with a GNN that uses them — a doubly equivariant model.

\[ A_{\text{rel}}=E_h^\top D_h^{-2}E_h+E_t^\top D_t^{-2}E_t,\qquad \mathbf z_r=\text{GNN}_{\text{rel}}(A_{\text{rel}}),\qquad \mathbf h_v=\text{GNN}_{\text{ent}}(G,\{\mathbf z_r\}) \]

Lecture 8 · Graph Transformers

A transformer is a GNN on the complete graph; a graph transformer re-injects the real graph via tokens, positional encodings, and attention biases — and the positional encodings must respect the symmetries (sign/basis) of whatever spectral object they come from.

\[ \text{GraphAtt}(X)=\text{softmax}\!\Big(\frac{(X+P)W^Q\,\big((X+P)W^K\big)^\top}{\sqrt d}+C\Big)(X+P)W^V \]

\(P\): positional encodings (one row per node); \(C\): edge / shortest-path biases \(c_{ij}\). Setting \(C_{ij}=-\infty\) for non-edges recovers neighbourhood-restricted attention (GAT-like).

Lecture 10 · Knowledge Graph Embeddings

A KG embedding turns each relation into a geometric operation; the algebra of that operation (commutative or not, invertible or not, composable or not) decides which logical patterns of relations the model can represent.

\[ \text{TransE: } \mathbf h+\mathbf r\approx\mathbf t\qquad \text{DistMult: } \textstyle\sum_i h_ir_it_i\qquad \text{ComplEx: } \mathrm{Re}\sum_i h_ir_i\bar t_i\qquad \text{RotatE: } \mathbf h\circ e^{i\boldsymbol\theta_r}\approx\mathbf t \]

Lecture 6 · Theory of GNNs — How Expressive Are They?

A message-passing GNN is at most as powerful as the 1-WL test; it reaches that bound exactly when every aggregation is injective on multisets — which sum aggregation with MLPs (GIN) achieves and mean/max do not.

\[ \mathbf{h}_v^{(k+1)}=\text{MLP}^{(k)}\Big((1+\epsilon^{(k)})\,\mathbf{h}_v^{(k)}+\sum_{u\in N(v)}\mathbf{h}_u^{(k)}\Big) \]

GIN layer. For graph classification, GIN reads out with a sum over nodes at every layer and concatenates them (the paper's readout).

Warm-up: answer these before you read on

What is the relation graph and why does it help? from Lecture 15

A graph whose nodes are relations, connected when they share heads or tails; a GNN over it gives each relation an embedding from its structural role, so unseen relations get embeddings too.

Why do graph transformers need positional encodings more urgently than text transformers? from Lecture 8

In text a simple index encodes position; a graph has no canonical order, so without encodings the model sees only a bag of node features and cannot tell the graph structure at all.

Which pattern does DistMult fail and ComplEx fix? from Lecture 10

Antisymmetry (and inversion): DistMult's score is symmetric in h and t; the complex conjugate in ComplEx breaks that symmetry.

Why does the MLP in GIN matter? from Lecture 6

The universal-approximation theorem lets a one-hidden-layer MLP represent any injective multiset function; sum alone needs a well-chosen encoding of the inputs.

More questions from every session you have reached, with spaced repetition: the cumulative review.

In short

This guest lecture (NVIDIA's PyG team) argues that structured data + GNNs complement unstructured data + LLMs. The speakers' framing: an LLM pretrained for next-token prediction behaves much like an associative memory — great in distribution, prone to hallucination out of distribution; it is generative and non-deterministic. A GNN with \(N\) layers performs \(N\) hops of relational "logic", is deterministic, and adds almost no parameters relative to an LLM.

Two integration patterns. GNN feeds LLM (for token-level tasks like question answering): retrieve a relevant subgraph from a knowledge graph, encode it with a GNN, and inject that embedding into the LLM alongside the question — G-Retriever, a form of GraphRAG. LLM feeds GNN (for graph tasks on text-attributed graphs): use a language model to turn each node's text into features, then train a GNN — or co-train them as in GLEM.

Practical pieces in PyG: sentence transformers for node/edge features, k-NN + n-hop retrieval pruned by a prize-collecting Steiner tree, GRetriever, GLEM, and TXT2KG for building KGs from raw documents with an LLM. A Neo4j case study reports doubling Hits@1 on the STaRK-Prime benchmark (0.16 → 0.32) over an agentic GraphRAG.

The picture: G-Retriever (GNN feeds LLM)

GraphRAG with a GNN encoder "Who is the sharedcoworker of A and B?" tokenise + embed 1 KG (millionsof nodes) k-NN seeds +n-hop expand PCST prune(dozens) query embedding guides retrieval 2 GNN(e.g. GAT) proj. 3 graph token + question tokens 4 LLM decoder(LoRA / full FT) "Arno S." 5

How to read it (hover a step)

  1. Tokenise and encode the question with the LLM's encoder (cost \(O(n^2)\) in tokens).
  2. Retrieve a relevant subgraph: embed nodes/edges with a sentence transformer, take k-NN seeds to the query, expand \(n\) hops (thousands of nodes), then prune with a prize-collecting Steiner tree to a small connected subgraph (dozens of nodes).
  3. Encode the subgraph with a GNN — almost free compared with the LLM — and project to the LLM's embedding size. (Optionally also pass the textified subgraph as text.)
  4. Jointly embed: the graph embedding acts as a soft prompt token prepended to the question tokens.
  5. The LLM decoder generates the answer. Training options (best → worst): full fine-tune, LoRA, frozen LLM.

1 · The argument: LLMs as associative memory

The speakers' case (present it to yourself as a position, not settled fact):

  • LLMs are pretrained for single-hop logic: given context, predict the next token — close to an associative memory. Toy: learn "2, 4, 6, 8…". A human learns "add 2"; an associative memory stores 2→4, 4→6 … and fails out of distribution.
  • Generative ⇒ non-deterministic: learn a distribution and sample, so one prompt may have several plausible outputs; with ambiguous training data ("2,4,6,8" and "2,6,18,54"), "2 → ?" is genuinely undetermined → plausible-sounding hallucinations; in code, stitched-together correct fragments often don't compose.
  • LLMs ≈ associative memory; the (1 − e)ⁿ argument. slide 7 ↗
  • LeCun's "auto-regressive models are doomed" slide: if each token has error probability \(e\), \(P(\text{correct})=(1-e)^n\) decays exponentially with length \(n\) (assuming independent errors).
  • GNNs: \(N\) layers = \(N\) hops of relational reasoning; deterministic; semi-orthogonal information; tiny vs LLMs (a transformer layer is itself a GNN on a complete word graph).
Honest counterpoint

These are contested claims. The \((1-e)^n\) argument assumes independent, uncorrectable errors — but models can self-correct, plan and verify, and chain-of-thought / tool use change the error model. Large models do show some out-of-distribution generalisation (e.g. in-context learning of novel functions), and "associative memory vs reasoning" is an active empirical debate (cf. Dziri et al. 2023, "Faith and Fate", which the slide cites, versus later work on reasoning models). The strong, uncontroversial point is narrower: retrieving the right structured facts and multi-hop composition over them is a weakness that explicit graph structure helps with.

2 · VectorRAG vs GraphRAG

RAG (retrieval-augmented generation): fetch relevant context at inference time and give it to the LLM.

  • VectorRAG: retrieve top-\(K\) documents by embedding similarity. Good enough when the answer lives in a single document.
  • GraphRAG: retrieve a relevant subgraph. Good when the answer requires multiple documents/facts connected through shared entities (multi-hop).

The org-chart example: "Who is the shared coworker between Bob Joe and Ronald Coleyman?" Given the edge list as text, a plain LLM answers wrongly; GNN+LLM answers correctly (Arno Swarzfinger) — the answer requires composing two "works.with" edges.

VectorRAG vs GraphRAG; the org-chart question. slide 14 ↗

From text to a PyG graph

PyG needs a feature vector per node (and optionally per edge), but KG entities and relations are short phrases, e.g. (cats, eat, dogs). Use a sentence transformer: model(List[str]) → Tensor, called ~3 × #edges times (head, relation, tail). Small LMs (e.g. ModernBERT) are enough for short phrases — large LMs only matter for long, complex text.

Retrieval details

Retrieval: k-NN and n-hop, then PCST pruning. slide 26 ↗

From a remote KG with millions of nodes: k-NN seeds + \(n\)-hop neighbours (fan-out \(f\)): cost \(O(X\cdot K\cdot f^n)\) → thousands of nodes; then PCST (prize-collecting Steiner tree) pruning, a similarity-based traversal that is linear on thousands of nodes → dozens of nodes.

What is a prize-collecting Steiner tree, and why is it a sensible pruning objective?

Given node "prizes" (relevance to the query) and edge costs, find a connected tree maximising total prize minus total edge cost (equivalently, minimising cost plus prizes of excluded nodes). Connectivity matters: the LLM needs a coherent chain of facts, not a bag of individually relevant nodes. It's NP-hard in general, but fast approximations (Goemans–Williamson-style) work well at this scale — G-Retriever uses exactly this.

3 · GNN feeds LLM vs LLM feeds GNN

GNN feeds LLMLLM feeds GNN
Dataprompt conditioned on a graphgraph whose nodes/edges carry text (or images)
Tasktoken-level (question answering, generation)graph learning (node classification, link prediction)
Flowgraph → GNN → GNN_out; (GNN_out + prompt) → LLM → answerLM/vision transformer → node/edge features → GNN → prediction
ExampleG-Retriever, PyG-RAGGLEM on OGBN-Products

GLEM (LLM feeds GNN)

GLEM pipeline: LM and GNN trained in alternation. slide 28 ↗

State of the art for node classification on text-attributed graphs (TAGs) like OGBN-Products. GLEM alternates, EM-style, between training the language model (using the GNN's predictions as pseudo-labels) and training the GNN (using LM-derived features and pseudo-labels) — so text understanding and graph structure teach each other without the cost of joint end-to-end training. PyG's implementation is ~7× faster than the original code, with a TAGDataset interface and optional LoRA fine-tuning.

4 · Building it in PyG

from torch_geometric.nn import GAT
from torch_geometric.llm.models import LLM, GRetriever      # torch_geometric.nn.models in older versions
gnn = GAT(in_channels=1024, hidden_channels=1024, out_channels=1024, num_layers=4, heads=4)
llm = LLM(model_name="meta-llama/Meta-Llama-3.1-8B-Instruct")
model = GRetriever(llm=llm, gnn=gnn)
loss = model(batch.question, batch.x, batch.edge_index, batch.batch,
             batch.label, batch.edge_attr, batch.desc)        # desc = textified subgraph
answers = model.inference(batch.question, batch.x, batch.edge_index, batch.batch,
                          batch.edge_attr, batch.desc)
  • TXT2KG (PyG 2.7): most RAG datasets are unstructured text; an LLM with a carefully engineered prompt + Python filters extracts (entity, relation, entity) triples.
  • PyG-RAG = GraphRAG + VectorRAG combined; reported adoption in industry. On a multi-hop synthetic Q&A over the lecture corpus, GNN+LLM variants outperform basic, agentic and graph-only RAG.
  • Multi-hop QA accuracy: GNN+LLM vs RAG variants. slide 38 ↗
  • More modalities: the "GNN embeddings as an LLM prefix" idea is general — molecules (MoleculeGPT: "talk to your molecule"), customer databases (talk to your data), hyperlinked documents; node features can be text, code, images, audio, video, molecule/cell embeddings.
  • Combine unstructured and structured graph data. slide 45 ↗
  • Structured (KG / relational DB) data is more accurate than unstructured text and likely covers different knowledge; enterprises have both — combine them, with a separate GNN per graph type.

The mathematics, step by step

This session is mostly system design, and its formulas describe a pipeline rather than a theory: retrieve a small subgraph that is relevant to a question, encode it with a GNN, and hand the result to a language model as if it were a few extra words. Each card is one stage, with the dimensions written out, plus the arithmetic of why multi-step questions are hard for a model that answers in one go.

Symbols used in this session

symbolmeaningwhat kind of object
\(q\)the question, as textstring
\(\mathbf e_q,\ \mathbf e_n\)text embeddings of the question and of the description of node (or edge) \(n\)vectors in \(\mathbb R^{d_t}\)
\(G_q=(V_q,E_q)\)the retrieved subgraph for the questionsmall connected graph
\(\text{prize}(n)\)reward for including a node or edge in the subgraph, from its retrieval ranknon-negative number
\(C_e\)cost of including one edgepositive number
\(\text{Pool}\)mean over the node embeddings of the subgraphfunction
\(W\)projection from the GNN's dimension to the language model's token dimension\(d_{LLM}\times d_{GNN}\) matrix (or a small MLP)
\([\,\cdot\,;\,\cdot\,]\)concatenation of token sequencesoperation
\(p\)probability that the model gets one reasoning step rightnumber in \((0,1)\)

1Retrieval by similarity

\[ \text{kNN}_q=\underset{n\in V\cup E}{\text{top-}k}\ \cos(\mathbf e_q,\mathbf e_n),\qquad \cos(\mathbf a,\mathbf b)=\frac{\mathbf a^\top\mathbf b}{\lVert\mathbf a\rVert\,\lVert\mathbf b\rVert} \]

In words. Embed the question and the text of every node and edge with the same text encoder. Keep the \(k\) nodes and \(k\) edges whose embeddings point most nearly in the same direction as the question's.

Why it has this form. The whole graph does not fit into a prompt, and most of it is irrelevant to any one question. Cosine similarity of text embeddings is a cheap first filter that can be answered from a pre-built index without touching the language model. It finds items that mention what the question mentions; it does not find the items that connect them, which is the next card's job.

With numbers. \(\mathbf e_q=(1,0)\). Node A: \((0.8,0.6)\), cosine \(0.8\). Node B: \((0.1,1)\), cosine \(0.1/1.005=0.10\). Node C: \((3,1)\), cosine \(3/\sqrt{10}=0.95\). Top-2: C and A. The length of C's vector did not matter, only its direction.

Watch out. Similarity retrieval alone returns isolated pieces. A question about how two things are related needs the path between them, whose nodes may not resemble the question at all.

2Connecting the pieces: prize-collecting Steiner tree

\[ G_q=\underset{S\subseteq G,\ S\text{ connected}}{\arg\max}\ \sum_{n\in V_S}\text{prize}(n)+\sum_{e\in E_S}\text{prize}(e)-C_e\cdot|E_S| \]

In words. Among all connected subgraphs, pick the one that collects the most prize from relevant nodes and edges after paying a fixed cost for every edge it uses.

Why it has this form. The prize of an item is high if it ranked high in retrieval (rank 1 gets \(k\), rank 2 gets \(k-1\), …, items outside the top \(k\) get 0). Connectivity forces the subgraph to include the bridging nodes between relevant items even though their own prize is zero. The cost per edge keeps the subgraph small: a far-away item is included only if its prize exceeds the cost of the path to it. The problem is NP-hard, and a fast approximation algorithm is used.

With numbers. Two retrieved nodes with prizes \(4\) and \(3\), joined by a path of 2 edges through an unretrieved node; \(C_e=1\). Taking both: \(4+3-2=5\). Taking only the first: \(4\). Both are kept, together with the bridge. If the path had 4 edges: \(4+3-4=3<4\), and the second node would be dropped.

Watch out. The edge cost is a knob with a direct effect on the answer: too high and the connecting facts are cut away, too low and the prompt fills with irrelevant neighbours.

3The graph as a soft prompt

\[ \text{answer}=\text{LLM}\Big(\big[\,W\cdot\text{Pool}(\text{GNN}(G_q))\,;\ \text{Embed}(\text{text of }G_q)\,;\ \text{Embed}(q)\,\big]\Big) \]

In words. Run a GNN on the retrieved subgraph, average its node embeddings into one vector, project that vector to the size of a word embedding, and put it in front of the embedded text of the subgraph and of the question. The language model reads the result as one sequence.

Why it has this form. A language model's input is a sequence of vectors of dimension \(d_{LLM}\); it does not care whether a vector came from a word. The projected graph vector is a 'soft token': an input position that carries the subgraph's structure, which a list of triples written as text conveys poorly. Only the GNN and \(W\) are trained (and optionally small adapters in the LLM); the gradient of the answer's loss flows back through the frozen LLM into them, so they learn to produce a token the LLM can use.

With numbers. GNN output dimension \(1024\), LLM token dimension \(4096\): \(W\) is \(4096\times1024\), about 4.2 million numbers, against billions in the frozen LLM. A question of 20 tokens and a subgraph description of 300 tokens become a sequence of \(1+300+20=321\) vectors.

Watch out. The textual description of the subgraph is still included: the single soft token complements the text and does not replace it.

4The other pattern: a language model makes the node features

\[ \mathbf x_v=\text{LM}(\text{text}_v),\qquad \mathbf h_v=\text{GNN}\big(\{\mathbf x_u\}_{u\in V},\ A\big)_v,\qquad \hat y_v=\text{softmax}(\mathbf W\mathbf h_v) \]

In words. Here the roles are reversed: the language model reads each node's text once and outputs a feature vector; an ordinary GNN then does the prediction over the graph.

Why it has this form. On a graph where each node has text (papers, products, posts), the classical features were bag-of-words counts. A language-model embedding carries far more of the meaning, and it is computed once and stored, so the expensive model is not in the training loop. The GNN then adds what the text of a single node cannot know: what its neighbours say. Pattern one (previous card) ends in generated text, this pattern ends in a label or a score.

With numbers. 100,000 products with descriptions. One pass of the LM gives a \(100{,}000\times768\) feature matrix. A 2-layer GNN with hidden size 256 on top has about \(768\cdot256+256\cdot C\) weights, a few hundred thousand, and trains in minutes.

Watch out. With frozen LM features, the encoder never learns which aspects of the text matter for the task; fine-tuning the LM together with the GNN helps but costs the efficiency.

5Why multi-hop questions break a single-shot model

\[ \Pr(\text{all } k \text{ hops correct})=p^{\,k} \]

In words. If each step of a chain of reasoning succeeds with probability \(p\), independently, the whole chain of \(k\) steps succeeds with probability \(p\) multiplied by itself \(k\) times.

Why it has this form. A question such as 'which drugs target proteins associated with disease X?' composes two facts. A model that must recall each fact from its weights can fail at each step, and the errors multiply. A graph makes each hop a lookup along an edge, which is exact, so the chain's reliability no longer decays with its length; the language model is left with the part it is good at, reading the question and phrasing the answer.

With numbers. \(p=0.9\): one hop \(0.90\), two hops \(0.81\), three hops \(0.73\), five hops \(0.59\). With \(p=0.7\): three hops \(0.34\).

Watch out. Independence of the steps is a simplification; the point is the direction of the effect, not the exact number.

Check yourself

Questions from the lecture, in order. Answer each one in your head (or on paper) before you open it. If one stumps you, follow the link to the walkthrough block it comes from.

Check yourself: why might a 10M-parameter GNN help an 8B LLM so much? show answer

Hint: the GNN sees the relational structure directly, in a form trained for this task; the LLM only sees text.

from Motivating result: the Neo4j case study

Check yourself: which step would you remove to save the most compute, and what would you lose? show answer

Removing 2a shortens the prompt a lot, but the LLM then has only a compressed vector, not the exact entity names.

from GNN feeds LLM: the G-Retriever pipeline

Check yourself: in the org-chart example of slide 14, which node would top-\(K\) retrieval for "Bob Joe" and "Ronald Coleyman" likely miss, and why would PCST keep it? show answer

Arno Swarzfinger: his name is not in the question, but he is the only link between the two.

from The retrieval algorithm: k-NN, n-hop, then PCST

Check yourself: for each task, which direction fits, GNN-feeds-LLM or LLM-feeds-GNN? show answer

(a) Answer "which drugs interact with protein X's pathway?" in natural language. (b) Classify Amazon products into categories using their descriptions and co-purchase links. (Answers: (a) GNN feeds LLM, the output is tokens; (b) LLM feeds GNN, the output is a node label.)

from Structured vs unstructured data, graph transformers, conclusion

Lecture walkthrough reference · slide by slide · opens on demand

The whole lecture in order, grouped by topic. Every drawing on the slides is redrawn here as a clean figure (click the step buttons where a figure has them), the heading of each block links to the matching pages of the official PDF, and the Review section after the walkthrough ties this session to the earlier ones. Read this and you do not need the deck.

  1. Motivating result: the Neo4j case study
  2. LLMs as associative memory
  3. GNNs: multi-hop, small and deterministic
  4. Where LLMs fit, and why GraphRAG
  5. GNN feeds LLM: the G-Retriever pipeline
  6. From a text KG to a PyG graph: sentence transformers
  7. The retrieval algorithm: k-NN, n-hop, then PCST
  8. LLM feeds GNN: text-attributed graphs and GLEM
  9. G-Retriever in PyG: setup, loss and inference
  10. Building the KG with an LLM: TXT2KG and PyG-RAG
  11. Next steps and more modalities
  12. Structured vs unstructured data, graph transformers, conclusion

Motivating result: the Neo4j case study slides 4 ↗

Slide 4, the Neo4j case study on STaRK-Prime: G-Retriever in PyG 2.6 against agentic GraphRAG systems. slide 4 ↗

This is a guest lecture by NVIDIA's PyG (PyTorch Geometric) team. It starts with a result, to show why combining GNNs with LLMs is worth the effort.

Slide 4. Neo4j is a graph database company (it stores data as nodes and relationships and queries them with the Cypher language). They used PyG 2.6's G-Retriever (explained later in this lecture) on STaRK-Prime, a question-answering benchmark built on a biomedical "semi-structured knowledge base". The figure at the bottom shows that knowledge base: node types such as Gene, Drug, Disease, Pathway, Protein, Anatomy, Phenotype and Molecular function, linked by relations like "carrier", "interact with", "indication/contraindication", "expression present/absent" and "associated with". Each node also carries free text, for example a description of the gene GPANK1 or of the disease GM1 gangliosidosis type I. So the answer to a question can depend both on text and on graph structure.

  • Result: Hits@1 doubled, from 0.16 to 0.32. The 0.16 baseline is an agentic GraphRAG system using a 7B LLM (an LLM that issues graph queries step by step); the 0.32 system is the PyG GNN+LLM solution.
  • The PyG solution is small: Llama 3.1-8B fine-tuned with LoRA plus a 10M-parameter GAT.
  • It even beats agentic GraphRAG built on much larger frontier models: Claude-3-Opus (0.18) and GPT-4-Turbo (0.20).

Recall that Hits@1 is the fraction of questions where the top-ranked answer is correct. The message of the slide: adding a small trained GNN that reads the graph helped more than using a bigger LLM that only "talks to" the graph through text queries.

Check yourself: why might a 10M-parameter GNN help an 8B LLM so much? show answer

Hint: the GNN sees the relational structure directly, in a form trained for this task; the LLM only sees text.

LLMs as associative memory slides 5-7 ↗

Slides 5–7: the speakers' position that LLMs are single-hop associative memories, and LeCun's exponential-error argument against auto-regression. slides 5-7 ↗

Slide 5 reviews the transformer (the figure is the encoder–decoder diagram from "Attention Is All You Need": input and output embeddings with positional encoding, stacked multi-head attention and feed-forward blocks, then a linear layer and softmax giving output probabilities). The speakers' claims:

  • LLMs are excellent at predicting the next token in a sequence.
  • In their view, progress from "attention is all you need" alone is plateauing.
  • LLMs are pretrained for single-hop logic: given context tokens, predict the next tokens. The speakers call this associative memory: it works in distribution but fails out of distribution, and NLP, robotics, medicine and other fields contain infinitely many out-of-distribution tasks.

Slide 6 gives a toy picture. Suppose the goal is to learn the sequence "2, 4, 6, 8, 10, 12, 14, …".

  • General (human) intelligence learns the rule "given a number, return that number + 2". This never fails out of distribution.
  • An associative memory model instead stores, for 500 GB of numbers, the next token: 2→4, 4→6, 6→8, … At test time it passes on numbers it has seen and fails on new ones: the output is undefined, so it hallucinates.

The speakers' claim is that today's LLMs are closer to associative memory than to human intelligence. (This is a position, not a theorem; treat it as the motivation of the talk.)

Slide 7 quotes Yann LeCun's slide "Auto-regressive generative models suck!". The argument: let \(e\) be the probability that any produced token takes the answer outside the set of correct answers. If errors are independent, the probability that an answer of length \(n\) is correct is

\[ P(\text{correct}) = (1-e)^n , \]

which decays exponentially in \(n\). The pie chart shows the "tree of all possible token sequences" as a large disk and the "subtree of correct answers" as a thin red slice: one wrong token can push you out of the slice for good. LeCun concludes that auto-regressive LLMs cannot be made factual or controllable without a major redesign (see also Dziri et al., arXiv:2305.18654).

The independence assumption is strong: real models can correct themselves, and errors are correlated. The formula is an intuition for why long, precise outputs are fragile, not an exact law.

GNNs: multi-hop, small and deterministic slides 8-11 ↗

Slides 8–11: what the GNN brings to the pair: multi-hop relational reasoning, determinism, and a tiny parameter budget. slides 8-11 ↗

Slide 8 recalls what a GNN is (figure from Matthias Fey's 2023 Graph Learning Conference talk, plus a QR code to the "GNN 101" visualizer from the University of Minnesota). GNNs update node representations by repeatedly transforming and aggregating representations of direct neighbors. The neural message passing scheme computes, for a node, messages \(\text{Message}(h_i^{(\ell)}, h_j^{(\ell)}, e_{ij}^{(\ell)})\) from each neighbor \(j\) and aggregates them. This gives data-dependent computation graphs, and generalizes architectures from CNNs (grids) to Transformers (complete graphs) to general GNNs.

Slide 9. Three points:

  • An \(N\)-layer GNN performs \(N\) hops of "logic": each layer passes information one hop. The picture shows node A's 2-hop computation graph (A ← B, C, D, E; those ← their own neighbors).
  • GNNs can improve LLM accuracy because they carry semi-orthogonal information: structure that the text alone does not show.
  • \(\text{size(LLM)} \gg \text{size(GNN)}\). Quoting Jure Leskovec, "a Transformer layer can be seen as a special GNN that runs on a fully connected 'word' graph". So adding a GNN to an LLM system adds almost no parameters.

Slide 10: GNNs are deterministic, LLMs are not. For a given input, most GNNs output the same answer every time. LLMs are generative: they learn a distribution and then sample outputs that fit it. One prompt can have two or more "right" answers, so there is a high chance of a plausible-sounding hallucination. Toy example: train an LLM on two sequences, 2, 4, 6, 8 and 2, 6, 18, 54. What should it predict after "2"? Both 4 (add 2) and 6 (multiply by 3) fit the training data.

Slide 11: the real-world version. For a task plus a Python solution there are almost always many valid solutions. An LLM can produce output that looks valid but has issues, because combining random chunks from correct codebases often does not give a correct program. Consequences: developers using AI spend a lot of time debugging, and severe bugs can slip through (crashes, security holes).

Where LLMs fit, and why GraphRAG slides 12-14 ↗

Slides 13–14: retrieve documents, or retrieve a subgraph; the made-up org chart where only the graph-aware system finds the shared coworker. slides 13-14 ↗

Slide 12: strengths and weaknesses. Basic LLMs are great for creative tasks that do not need absolute precision (writing, art). They are not ideal for precise tasks such as coding or high-impact decisions. Also, LLMs are running out of public data; GNNs open a whole new world of data (relational, structured, often private). GNNs will not solve all problems, but they are a step in the right direction.

Slide 13: VectorRAG vs GraphRAG. RAG = Retrieval-Augmented Generation: before answering, retrieve relevant context and give it to the LLM.

  • VectorRAG: embed all documents; retrieve the top-\(K\) documents whose embedding vectors are most similar to the query. Good enough when the answer is inside a single document.
  • GraphRAG: retrieve a relevant subgraph. Good when the answer needs several documents with related entities, that is, multi-hop reasoning. The diagram previews the G-Retriever pipeline used later.

Slide 14: a made-up NVIDIA org chart. Ten people (nodes 0–9: Ron Wonald, Jensen Huang, Ronald Coleyman, Arno Swarzfinger, Bob Joe, Joe Bob, Richard Preor, Breance Owls, Justin Brogard, Ash Katchoop) and typed edges such as "reports.to", "leads", "mentors" and "works.with". The graph is given to the model as two text tables, node_id,node_attr and src,edge_attr,dst. Question: "Who is the shared coworker between Bob Joe and Ronald Coleyman?" The answer is Arno Swarzfinger, because of the edges 4,works.with,3 (Bob Joe – Arno) and 3,works.with,2 (Arno – Ronald Coleyman). The slide reports: LLM alone is wrong; GNN+LLM is correct.

Why is this hard for an LLM? The two needed edges are scattered among the edge list, and the model must join them on the shared node id 3 and map ids back to names: a 2-hop query. The figure also has distractors with similar names (Bob Joe vs Joe Bob, Ron Wonald vs Ronald Coleyman). A 2-layer GNN does exactly this kind of 2-hop join.

GNN feeds LLM: the G-Retriever pipeline slides 15-22 ↗

Slides 16–22, the G-Retriever pipeline built up step by step (GNN feeds LLM). slides 16-22 ↗

Slide 15: a history lesson. "Attention Is All You Need" appeared on arXiv on June 12, 2017; the GraphSAGE paper appeared on June 7, 2017, five days earlier. Since then industry has put most of its effort into LLMs, while a small but strong PyG community grew in academia, plus a small group of companies using GNNs (Pinterest, Kumo, Spotify, …). PyG's GNN+LLM work aims to combine the two lines and move AI systems past the limits of LLMs.

Slides 16–21 build up one diagram, adding one step per slide (the red box marks the new part). This is G-Retriever (arXiv:2402.07630), a GraphRAG method where the GNN feeds the LLM. Given a natural-language query at inference time:

  1. Encode the query (slide 17): tokenize the query and encode it with the LLM encoder. Cost: LLM complexity is \(O(n^2)\) in the number of tokens \(n\), because attention compares all token pairs.
  2. Retrieve and encode a subgraph (slide 18): retrieve a subgraph of the knowledge graph (KG) relevant to the query, take its node/edge features, and encode it with a GNN encoder. The slide says GNN complexity is "~free" compared with the LLM. (Node/edge embeddings are covered on slides 23–25 and the retrieval algorithm on slide 26.)
  3. (2a, slide 19) Optionally also turn the retrieved subgraph into text (the textified graph, like the tables on slide 14) and pass it into the LLM encoder with the query.
  4. Jointly embed (slide 20): concatenate the GNN embedding with the LLM token embeddings. In practice the graph embedding is projected to the LLM's embedding size and placed in front of the prompt, like a "soft prompt" token.
  5. Decode (slide 21): the LLM decoder reads the joint embedding and generates the natural-language response.

Slide 22: training options, best to worst test accuracy: (1) full fine-tuning of the LLM, (2) LoRA fine-tuning of the LLM (next best), (3) frozen LLM (least good). In all cases the GNN (and projection) are trained, so gradients from the answer tokens flow back into the GNN.

Intuition: the textified graph gives the LLM the raw facts, but the LLM must still do multi-hop joins in its \(O(n^2)\) attention. The GNN embedding gives it a pre-digested, structure-aware summary that costs almost nothing.

Check yourself: which step would you remove to save the most compute, and what would you lose? show answer

Removing 2a shortens the prompt a lot, but the LLM then has only a compressed vector, not the exact entity names.

From a text KG to a PyG graph: sentence transformers slides 23-25 ↗

Slides 23–25: PyG needs feature vectors, a text KG has phrases; a sentence transformer bridges them. slides 23-25 ↗

Slide 23. PyG expects a feature vector for each node and, optionally, for each edge. But in a text KG, entities and relations are short phrases. Example triple: (cats, eat, dogs). So we need a model \(\text{Model}(\text{str}) \to \text{feature vector}\).

Slide 24: sentence transformer. A sentence transformer maps a list of strings to an embedding tensor: \(\text{model}(\text{List[str]}) \to \text{Tensor}\). The code on the slide loads SentenceTransformer(model_name='sentence-transformers/all-roberta-large-v1') and moves it to the GPU if available. Cost: the model is called \(3 \times \text{num\_edges}\) times, because each edge needs the head entity, the relation and the tail entity embedded. So use a small language model (SLM) such as ModernBERT for efficiency.

Slide 25: why small LMs are fine here. Small LMs understand short phrases well enough; large LMs are only needed for long or complex text. Future work: measure the trade-off between SLM and LLM encoders. The latest PyG also supports Vision Transformers, so image attributes can be encoded the same way.

In practice you embed each distinct entity and relation string once and reuse it, so the real cost is closer to the number of distinct strings than to \(3\times\) the number of edges.

The retrieval algorithm: k-NN, n-hop, then PCST slides 26 ↗

Slide 26, the retrieval algorithm: similarity seeds expanded by n hops, then a prize-collecting Steiner tree keeps a small connected subgraph; the interactive figure below steps through it. slide 26 ↗

Slide 26 zooms into the "Retrieve Subgraph Context" box of the G-Retriever diagram. The input is a remote KG with millions of nodes and the prompt. Retrieval runs in two stages:

  1. k-NN and n-hop neighbors. Embed the query; find the \(K\) nodes (and edges) most similar to it; expand each seed by \(n\) hops. This gives an untrimmed subgraph of thousands of nodes. Cost: with \(X\) seed nodes, \(n\) hops and fanout \(f\), it is \(O(X \cdot K \cdot f^n)\), exponential in the number of hops, like neighbor sampling in GraphSAGE.
  2. Prize-Collecting Steiner Tree (PCST). Prune the subgraph to a connected subgraph of dozens of nodes. The slide calls it "similarity-based graph traversal"; it is linear in the thousands of nodes, so "free" compared with the LLM.

What PCST does (background from the G-Retriever paper, not on the slide): each node and edge gets a prize that is larger when it is more similar to the query; each edge also has a cost. PCST finds a connected subgraph \(S\) that maximizes

\[ \sum_{v\in S}\text{prize}(v) + \sum_{e\in S}\text{prize}(e) - \text{cost}(S). \]

Connectedness matters: a relevant entity is only useful together with the path that links it to the other relevant entities. Pure top-\(K\) retrieval can return relevant but disconnected fragments; PCST keeps the "bridges" even when a bridge node itself is not very similar to the query.

Check yourself: in the org-chart example of slide 14, which node would top-\(K\) retrieval for "Bob Joe" and "Ronald Coleyman" likely miss, and why would PCST keep it? show answer

Arno Swarzfinger: his name is not in the question, but he is the only link between the two.

LLM feeds GNN: text-attributed graphs and GLEM slides 27-31 ↗

Slides 27–31: the two directions of coupling, and GLEM for text-attributed graphs. slides 27-31 ↗

Slide 27 contrasts the two directions:

  • GNN feeds LLM. Data: a prompt conditioned on a graph. Tasks: token-level tasks, for example question answering. Flow: Graph → GNN = GNN_out; then (GNN_out + prompt) → LLM = answer tokens.
  • LLM feeds GNN. Data: a graph where every node/edge has tokens (text) attached. Tasks: graph learning, for example node classification or link prediction. Flow: compute a feature vector for each node/edge with a sentence or vision transformer, then feed the graph to a GNN.

Slide 28: GLEM (arXiv:2210.14709) is described as the state of the art for node classification on text-attributed graphs (TAGs), for example ogbn-products (Amazon products whose descriptions are text). The figure: raw text of node objects is tokenized into a text-attributed graph. Then an EM loop runs:

  • E-step (yellow): train the language model on the text of each node; it outputs predictions used as pseudo-labels.
  • M-step (blue): train the GNN on the graph; for the M-step, the LM's pseudo-outputs are concatenated with the original node features. The GNN's predictions become pseudo-labels for the next E-step.
  • Pseudo-labels from each model serve as augmented training data for the other; the final output is the external prediction.

Why alternate instead of training one big LM+GNN end to end? Back-propagating through a large LM for every node in a big graph is too expensive. Alternating lets each model learn from the other: the LM learns what the graph "thinks" about a node, and the GNN gets text-aware inputs. Unlabeled nodes still contribute through pseudo-labels, which is a form of semi-supervised learning (compare label propagation in Chapter 19 of the notes).

Slide 29: GLEM in PyG. The PyG implementation is 7× faster than the original paper's code on ogbn-products. It comes with a new TAG (text-attributed graph) interface, optional LLM fine-tuning with LoRA (via Hugging Face's PEFT library), and an example at examples/llm/glem.py.

Slide 30: TAG usage. Load PygNodePropPredDataset('ogbn-products'), get the split, and wrap it: TAGDataset(root, dataset, "prajjwal1/bert-tiny", token_on_disk=...). It takes a path, the dataset and the LM of your choice; optionally it saves tokens on disk.

Slide 31: GLEM setup. Build a GNN, for example GAT(in_channels=1024, hidden_channels=1024, num_layers=4, out_channels=num_classes, heads=4), then GLEM(lm_to_use='prajjwal1/bert-tiny', gnn_to_use=gnn, out_channels=num_classes, lm_use_lora=..., device=device). Options: use LoRA; choose the device (the default is CPU, which is very slow).

G-Retriever in PyG: setup, loss and inference slides 32-34 ↗

gnn = GAT(in_channels=1024, hidden_channels=1024, out_channels=1024, num_layers=4, heads=4)
llm = LLM(model_name="meta-llama/Meta-Llama-3.1-8B-Instruct")
model = GRetriever(llm=llm, gnn=gnn)                     # slide 32

loss = model(batch.question, batch.x, batch.edge_index, batch.batch, batch.label, batch.edge_attr, batch.desc)   # slide 33
answers = model.inference(questions, batch.x, batch.edge_index, batch.batch, batch.edge_attr, textified_graphs)  # slide 34

Slides 32–34 as code: 1024 matches the sentence-transformer width; the batch carries one subgraph per question, its label and a textified description.

Slide 32: setup. A G-Retriever model is an LLM plus a GNN:

  • gnn = GAT(in_channels=1024, hidden_channels=1024, out_channels=1024, num_layers=4, heads=4). The 1024 matches the sentence-transformer feature size; the output must later be projected to the LLM's hidden size.
  • llm = LLM(model_name="meta-llama/Meta-Llama-3.1-8B-Instruct")
  • model = GRetriever(llm=llm, gnn=gnn). GPU setup is automatic.

Slide 33: getting the loss. Calling model(...) in training mode returns the loss. Its arguments, one mini-batch of questions:

  • batch.question: list of question strings;
  • batch.x: node features, shape [num_nodes, num_features];
  • batch.edge_index: shape [2, num_edges];
  • batch.batch: which nodes belong to which question (each question has its own retrieved subgraph, packed into one big disconnected graph, as in PyG graph batching);
  • batch.label: list of answers (the target text);
  • batch.edge_attr: edge features, [num_edges, num_features];
  • batch.desc: list of text descriptions of each graph (the textified graph of step 2a).

The loss is the usual next-token cross-entropy on the answer tokens, given the graph embedding plus the question.

Slide 34: inference. model.inference(questions, batch.x, batch.edge_index, batch.batch, batch.edge_attr, textified_graphs): the same inputs except the labels; edge attributes and textified graphs are optional but recommended.

Building the KG with an LLM: TXT2KG and PyG-RAG slides 35-39 ↗

Slides 35–37: build the KG with an LLM, then combine graph and vector retrieval. slides 35-37 ↗
Slide 38: accuracy of RAG variants judged by a 253B model; textifying a subgraph alone hurts, adding the GNN helps most. slide 38 ↗

Slide 35: knowledge graph creation. Most RAG datasets only have unstructured text. To use GraphRAG we need a KG, so the task is: unstructured text → KG in the triple format (entity_1, relation, entity_2). LLMs are specialized for unstructured text, so they are the ideal tool for this (the picture: documents → LLM → graph).

Slide 36: the TXT2KG class, released in PyG 2.7. It is prompt engineering plus Python filters. The system prompt asks the model to convert the text into a list of knowledge triples of the form ('entity', 'relation', 'entity'), separated by new lines, to output nothing else, to focus on key triples, and to reuse the same entities whenever possible (so that the triples link into one graph rather than many duplicates). Usage: loop over documents and call kg_maker.add_doc_2_KG(txt=context_doc).

Slide 37: GraphRAG + VectorRAG = PyG-RAG (torch_geometric.llm). The diagram is the G-Retriever pipeline with two additions: at the top, documents are turned into the KG by an LLM (TXT2KG); at the bottom, a Doc/Chunk Retrieval box (classic VectorRAG) feeds retrieved text chunks into the LLM encoder alongside the query and the textified graph. So the LLM gets three inputs: the GNN embedding, the textified subgraph and the raw text chunks. The slide says PyG-RAG is being adopted across Fortune 500 companies and inside NVIDIA; example code: examples/llm/txt2kg_rag.py.

Slide 38: accuracy on multi-hop synthetic Q&A for a lecture corpus. The bar chart shows accuracy judged by a 253B Nemotron-Ultra LLM, with Llama3-8B as the generator. Synthetic Q&A pairs were made with NVIDIA TrueQuery; the 253B Nemotron was used for TXT2KG and ModernBERT for vector embeddings. Approximate bar heights read from the plot:

  • Basic RAG ≈ 70; Basic RAG + fine-tuned LLM ≈ 77; Agentic RAG (NV-AIQ) ≈ 73;
  • Basic Graph RAG ≈ 59 (the lowest); Basic Graph RAG + fine-tuned LLM ≈ 77;
  • GNN+LLM RAG (also fine-tuned) ≈ 81–82, the best real system;
  • "Golden retrieval" ≈ 82–83: the upper bound ("speed of light"), where the generator is fed the same documents that were used to create each Q&A pair.

Lessons: naive GraphRAG (just textify a subgraph) can be worse than plain RAG; fine-tuning helps everything; and the GNN+LLM system comes close to perfect retrieval.

Slide 39: a "vibe-coded" GUI. To show the codebase is easy to build on, the PM (Santosh Bhavani) built a GUI with Cursor: "Text-to-Graph on NVIDIA DGX Spark" (build.nvidia.com/spark/txt2kg). The screenshot shows a dark interface with a large rendered knowledge graph.

Next steps and more modalities slides 40-44 ↗

Slides 40–44: the roadmap and the general "GNN as prompt prefix" pattern. slides 40-44 ↗

Slide 40: next steps for PyG's GNN+LLM work:

  • keep improving the codebase (speed, usability, accuracy, understandability);
  • accelerate retrieval with cuGraph + cuVS (GPU graph analytics and GPU vector search), to scale to a trillion edges and beyond;
  • align TXT2KG with KGGen (a Stanford tool for extracting KGs from text);
  • more modalities, new problems and new retrieval techniques.

Slides 41 and 44: the general idea. Using GNN embeddings as a prefix to a Transformer/LLM prompt is very general. Examples:

  1. graphs = molecules or cells; language task = biology, chemistry, drug discovery;
  2. graphs = customer data; task = "talk to your customer data";
  3. graphs = documents with hyperlinks; task = "talk to your docs".

Graphs can also mix modalities: Amazon products where each node has a text review and a photo; relational-database heterographs as in RelBench and Kumo.ai (Lectures 13–14). Node features could be text (natural language or code), images, audio, video, or molecule/cell embeddings.

Slide 42: a scientific GNN+LLM community sprint (biology and chemistry): the goal is to add GNN+LLM support for the sciences, with 3 biology papers and 1 chemistry paper reimplemented, to advance medicine and science (see examples/llm/README.md).

Slide 43: MoleculeGPT, "talk to your molecule". A user asks "How is the color and odor of molecule C1-CC-C(C-C1)C=O?" (a SMILES string) and the bot answers "It appears a clear colorless to yellow liquid with a bitter almond odor." A GNN encodes the molecular graph; its embedding is fed to the LLM through a Q-Former (the bridge module from BLIP-2; QR codes link to the PyG example, the MoleculeGPT paper and the Q-Former paper).

Structured vs unstructured data, graph transformers, conclusion slides 45-47 ↗

Slides 45–47: the accuracy spectrum from extracted to native graphs, and the lecture's conclusion. slides 45-47 ↗

Slide 45 draws a spectrum. On the left: unstructured documents turned into a KG by an LLM (TXT2KG): less accurate, because extraction makes mistakes. On the right: natively structured graph data such as relational databases (RelBench), hyperlinked web pages and molecules: highly accurate. In between: the two kinds likely cover different knowledge, and most enterprises have both. The proposal is to combine them, with a separate GNN per graph type.

Slide 46: graph transformers vs message passing (future). Today there are two kinds of GNN: traditional message passing and the newer graph transformers (with a QR code to a webinar). More graph transformers are coming to PyG; a future goal is to measure how they change the accuracy of the GNN+LLM systems above.

Slide 47: conclusion.

  • General AI rule: data is king. Example: even the best model cannot learn from randomly labelled data.
  • Key takeaway: structured data (GNN) + unstructured data (LLM) = better GenAI.
  • All of this is built and optimized in NVIDIA's PyG container (catalog.ngc.nvidia.com).
Check yourself: for each task, which direction fits, GNN-feeds-LLM or LLM-feeds-GNN? show answer

(a) Answer "which drugs interact with protein X's pathway?" in natural language. (b) Classify Amazon products into categories using their descriptions and co-purchase links. (Answers: (a) GNN feeds LLM, the output is tokens; (b) LLM feeds GNN, the output is a node label.)

Not shown (no new content): slides 1,2,3,48,49 — title page, exam and homework announcements, section title page, acknowledgements, thank-you page.

Review: what to keep from this session

Carried forward. Lecture 17 turns the LLM into an agent that queries structured knowledge; Lecture 19's wrap-up places graphs as the frontier beyond sequences.

Quick self-check

Why inject a GNN embedding instead of pasting the subgraph as text?

Text serialisation is long, order-dependent and loses structure; a GNN embedding is compact, permutation invariant and can be trained end-to-end with the LLM.

When is "LLM feeds GNN" the right pattern?

For node- and graph-level tasks on text-rich graphs where the labels depend on structure: the LLM gives good features, the GNN does the relational reasoning.

What is the hallucination argument for retrieval?

An LLM answers from associative memory; grounding it in retrieved facts constrains the answer to what the KG actually contains.

Key idea

Use each model for what it is good at: GNNs for precise, multi-hop composition over structured facts, LLMs for language understanding and generation — connected either by injecting a GNN's subgraph embedding into the LLM (GraphRAG) or by using an LM to featurise a text-attributed graph for a GNN.

\[ \text{answer}=\text{LLM}\Big(\big[\,W\cdot\text{Pool}(\text{GNN}(G_q))\,;\ \text{Embed}(q)\,\big]\Big),\qquad G_q=\text{PCST}\big(\text{kNN}_q\oplus n\text{-hop}\big) \]

Worked example: the shared-coworker question

Edges (subset): Bob Joe (4) —works.with→ Arno Swarzfinger (3); Arno (3) —works.with→ Ronald Coleyman (2); Arno (3) —works.with→ Richard Preor (6); plus many reports.to / leads / mentors edges.

  1. Query mentions "Bob Joe" and "Ronald Coleyman" → k-NN seeds = nodes 4 and 2 (and the relation "works.with").
  2. 2-hop expansion around both seeds includes node 3 (Arno), the only node adjacent to both via works.with.
  3. PCST keeps the connected tree {4 — 3 — 2} (high prize, low cost) and drops unrelated leads/reports edges.
  4. A 2-layer GNN on this tree places the "common neighbour" signal in the pooled embedding; the LLM decodes "Arno Swarzfinger".
  5. Given only the raw edge list as text, the LLM must perform the join itself — and often doesn't.

Strictly speaking: modern frontier LLMs can solve this small example from text; the advantage of the GNN path shows at scale (millions of facts, multi-hop chains) and with smaller, cheaper LLMs — as in the reported STaRK-Prime result where an 8B model + 10M-parameter GAT beat agentic GraphRAG with much larger frontier models.

Proof workshop: Three-terminal Steiner trees are spiders

One problem in olympiad style. Give it fifteen minutes on paper before you open the first hint; the hints are graded, so open them one at a time.

Problem. In a connected graph with unit edge weights, let \(S=\{s_1,s_2,s_3\}\). Prove that some minimum Steiner tree for \(S\) is the union of shortest paths from one vertex \(m\) to the three terminals, so its cost is \(\min_m\sum_{i=1}^3d(m,s_i)\). Deduce an \(O(|V|+|E|)\) algorithm.

Hint 1
Prune non-terminal leaves from an optimal tree: all leaves are now terminals, so there are at most 3. For a tree, \(\sum_v(\deg v-2)=-2\).
Hint 2
So at most one vertex has degree 3. Each "leg" from that vertex to a terminal must be a shortest path, otherwise replace it.
Solution
Take an optimal tree \(T\) and delete non-terminal leaves repeatedly: the cost does not increase, and all leaves are terminals, so \(T\) has \(\ell\le3\) leaves. From \(\sum_v(\deg v-2)=2(|V_T|-1)-2|V_T|=-2\), the leaves contribute \(-\ell\), so \(\sum_{\deg\ge3}(\deg v-2)=\ell-2\le1\): at most one vertex \(m\) has degree 3, and no vertex has higher degree. If none does, \(T\) is a path and we take \(m\) to be its middle terminal. Otherwise \(T\) is three paths from \(m\) to \(s_1,s_2,s_3\). Each path has length \(\ge d(m,s_i)\), so \(\mathrm{cost}(T)\ge\sum_id(m,s_i)\). The union of three shortest paths from \(m\) connects \(S\) with at most that many edges. So the optimum is \(\min_m\sum_id(m,s_i)\). Algorithm: three BFS runs, then a scan over \(m\). \(\square\)

Why it matters. Steiner trees are NP-hard in general, but GraphRAG retrieval usually starts from two or three seed entities, and then the exact answer is a few BFS runs. Two terminals give a shortest path (the notebook's 2-fact context); three give a spider. The general prize-collecting version used by G-Retriever is where approximation enters.

Sharper lens: hops, depth and a narrow channel

Not on the slides. Three or four points where the lecture rounds something off: the exact statement, a second way to see it, and where it stops being true. Each is short and has a pointer for going further.

second viewpoint

"N layers, N hops" is the GNN's limit; a transformer needs log N

The speakers contrast an LLM's "single-hop" prediction with a GNN's \(N\) hops in \(N\) layers. The theory says something sharper, in both directions. Message passing moves information one edge per layer, so composing \(k\) facts along a path needs at least \(k\) layers (Loukas, ICLR 2020, gives depth-times-width lower bounds of this kind), and Lecture 4 showed what long paths cost. Attention can read any position, so every item can replace its pointer by its pointer's pointer:

Sanford, Hsu and Telgarsky (ICML 2024) prove that depth \(O(\log k)\) is sufficient for a transformer to compose \(k\) hops and, by relating transformers to massively parallel computation, that it is also necessary under a standard conjecture in that field. A fixed-depth transformer answering in one pass is still bounded (it lies in the circuit class \(\mathsf{TC}^0\), Merrill and Sabharwal 2023); writing intermediate steps removes the bound, and with polynomially many steps of chain of thought a transformer can compute anything in \(\mathsf P\) (Merrill and Sabharwal, ICLR 2024).

So the failures on multi-hop questions are not a ceiling on what the architecture can represent. They are failures to find and line up the facts, which is what graph retrieval repairs: it puts a short, connected chain into the context. The GNN's contribution is exact local propagation over that small subgraph, not a monopoly on multi-hop reasoning.

where it breaks

One pooled vector is a narrow channel

In G-Retriever the GNN's output is pooled over the retrieved subgraph and projected to a single soft token. Dozens of nodes and typed edges pass through one vector: the bottleneck of Lecture 5's virtual node, placed between two models. The architecture does not rely on it alone. The same subgraph is also written into the prompt as text, and in the paper's own ablation removing that textual description costs clearly more accuracy than removing the graph encoder.

That gives the open question at the end of this page a concrete form. When you compare "GNN soft prompt" with "subgraph as text", control three things: the retrieval (identical subgraphs), the token budget, and the number of graph tokens (one pooled vector, or one token per node). The honest baseline for a GNN+LLM system is the same LLM with the same retrieved subgraph, serialised well.

precise statement

GLEM is variational EM, which is why alternating works

GLEM's alternation is not a heuristic. The target is the likelihood of the observed labels \(\log p(\mathbf y_L\mid\text{graph},\text{text})\), with the unknown labels \(\mathbf y_U\) as latent variables. The evidence lower bound needs a distribution \(q(\mathbf y_U)\) over them. E-step: the language model plays \(q\): it predicts each node's label from its own text only, trained on the true labels and on the GNN's current predictions for unlabelled nodes. M-step: the GNN plays \(p\): it is trained on the true labels and on the language model's pseudo-labels, using the graph.

The factorised \(q\) (one node at a time) is what makes this scale: the language model never needs neighbours in its context, and the GNN never needs gradients through the language model. The price is the usual one for mean-field EM: each model can confirm the other's confident errors, so the quality of the first pseudo-labels matters, and a held-out set must monitor both.

Lab: hands-on and practical tips

notebook · L16 LLMs + GNNs builds a company knowledge graph, compares VectorRAG with GraphRAG (Steiner-tree retrieval), trains a GNN reader on the retrieved subgraph, asks a real LLM through Ollama (answers cached), and uses an LLM to produce node features for a GNN.

Decide by query type, not by fashionThe GraphRAG-Bench figure above: graph retrieval wins on multi-hop questions and loses on simple lookups, at much higher token cost. For a social corpus: community summaries suit "what are the main narratives?"; plain retrieval suits "what did this account say on this date?".
Retrieval is three knobsk (seeds by embedding similarity), n (hops of expansion) and the Steiner-tree prize/cost trade-off. Step through the figure above; most failures come from n too large (distractors) or the prune too aggressive (seeds disconnected).
Cache every LLM callThe notebook caches answers by prompt hash in cache/llm_cache.json, so re-runs make no network calls and results are reproducible. Do the same, and keep server addresses in .env, never in the repo.
Let the LLM write code for structural questionsThe ICLR 2026 oral finding: an LLM that writes NetworkX or SQL over the graph beats one that reads a serialised neighbourhood, especially on long-text or high-degree graphs, and stays effective on heterophilous graphs. For X analysis, generate code, do not paste neighbourhoods into prompts.

Readings & lookup guide

No readings are assigned on the course site for this lecture; these are the papers the slides build on, ranked.

read first He et al. — G-Retriever: Retrieval-Augmented Generation for Textual Graph Understanding and Question Answering (NeurIPS 2024)

  • Read: §4 (indexing, retrieval, PCST subgraph construction, answer generation with a graph soft prompt), the GraphQA benchmark (§3), hallucination analysis.

LLM feeds GNN Zhao et al. — Learning on Large-scale Text-attributed Graphs via Variational Inference (GLEM, ICLR 2023)

  • Read: §3 (pseudo-likelihood variational EM: E-step trains LM, M-step trains GNN), results on ogbn-products/arxiv.

GraphRAG Edge et al. — From Local to Global: A Graph RAG Approach to Query-Focused Summarization (Microsoft, 2024)

  • A different GraphRAG: LLM-built entity graph + community detection (Leiden) + community summaries for global questions. Good contrast with G-Retriever's GNN encoding — and very relevant to SNA (community detection!).

benchmark & critique Wu et al. — STaRK: Benchmarking LLM Retrieval on Textual and Relational Knowledge Bases (NeurIPS 2024 D&B) · Dziri et al. — Faith and Fate: Limits of Transformers on Compositionality (NeurIPS 2023)

  • STaRK is the benchmark in the Neo4j case study. "Faith and Fate" is the evidence behind the "LLMs fail at compositional multi-hop reasoning" claim — read it critically alongside newer reasoning-model results.

Homework & deadlines

Colab 4 due Tue 12/1 · Colab 5 due Thu 12/3 · Project report due Thu 12/10 (no late periods)

Exam was Wed 11/18 (this lecture's material is in scope but not in the focus window). For a final project, a PyG GraphRAG on a domain KG is very feasible with the examples in examples/llm/.

Self-check

When is GraphRAG preferable to VectorRAG?

  1. When the answer is in one document
  2. When the answer requires combining facts about related entities across documents
  3. When there's no KG
  4. Always

Multi-hop, multi-document answers.

In G-Retriever, how does graph information enter the LLM?

  1. Only as text
  2. By fine-tuning the GNN only
  3. Through the loss
  4. As a projected GNN embedding (soft prompt) prepended to the question tokens (plus optional textified subgraph)

"Jointly embed the GNN embedding with the LLM embedding".

The PCST step in retrieval …

  1. prunes thousands of candidate nodes to a small connected, relevant subgraph
  2. computes node features
  3. trains the LLM
  4. finds shortest paths only

Prize = relevance, cost = edges; keeps connectivity.

GLEM is an example of …

  1. GNN feeds LLM
  2. graph generation
  3. LLM feeds GNN on text-attributed graphs
  4. KG embedding

LM and GNN co-trained via EM with pseudo-labels.

Which training option gave the best accuracy in the slides for GNN+LLM?

  1. Frozen LLM
  2. Full fine-tuning
  3. LoRA
  4. No GNN

Full FT > LoRA > frozen.

Flashcards (click to flip)

G-Retriever in 4 steps
Encode query → retrieve & PCST-prune subgraph → GNN encode → joint embed → LLM decode.
VectorRAG vs GraphRAG
Top-K docs by embedding vs relevant subgraph for multi-hop answers.
Text → node features
Sentence transformer (small LM suffices for short phrases).
GLEM
Variational EM alternating LM and GNN training on text-attributed graphs.
TXT2KG
LLM + prompt + filters extract (entity, relation, entity) triples from documents.
Speakers' core claim
Structured data (GNN) + unstructured data (LLM) = better GenAI.

History & the bigger picture

  • June 2017: GraphSAGE (June 7) and "Attention is all you need" (June 12) appear on arXiv five days apart. Industry poured its effort into the second; the PyG community grew around the first.
  • 2020 — RAG (Lewis et al.); 2021–2023 — KG-augmented LMs (QA-GNN, GreaseLM); 2024 — G-Retriever, Microsoft GraphRAG; GraphRAG becomes an industry buzzword.
Philosophy of mind · association vs inference

The "LLMs are associative memories" debate echoes an old one: Hume's associationism versus rationalist accounts of inference; connectionism versus symbolic AI (Fodor & Pylyshyn 1988 argued neural nets lack systematic, compositional structure). GNN+LLM systems are a pragmatic neuro-symbolic compromise: an explicit relational structure (the KG) supplies systematicity, the neural parts supply flexibility. For your research this is home turf — and a reminder to test such claims empirically rather than adopt either camp's rhetoric.

Classic SNA bridge

In this lectureClassic SNA counterpartWhat carried over, what changed
GraphRAG: extract, cluster (Leiden), summarise, answerCommunity detection (Girvan–Newman 2002; Louvain 2008; Leiden 2019) and the "content analysis of groups" traditionA 2024 LLM system has a 2002 SNA algorithm at its centre. Which communities Leiden finds (resolution, randomness) decides what the LLM "knows"; SNA knows how fragile that choice is (resolution limit, Fortunato & Barthélemy 2007).
Personalised PageRank retrieval (HippoRAG)Katz status; PageRank as a centrality (Brin & Page 1998, with roots in Seeley 1949)PPR with teleport α is the operator (I − (1−α)Â)⁻¹, the same one as the Friedkin–Johnsen equilibrium. Retrieval by spreading activation is opinion propagation with a different interpretation.
LLM as associative memory vs GNN as multi-hop logicCognitive social structures (Krackhardt 1987): what people believe the network is vs what it isAn LLM holds a fuzzy, aggregated picture of relations (a cognitive social structure); the KG holds the recorded ties. Krackhardt measured the gap between perceived and actual networks; GraphRAG engineers around it.
Text-attributed graphs; LLM features for nodesContent plus structure: ego-network studies with attribute data; "homophily on attributes"SNA combined who-talks-to-whom with what-they-say by hand coding. Sentence encoders make the "what they say" a vector; GLEM-style co-training learns the coupling.
TXT2KG: build a KG from documents with an LLMDiscourse network analysis (Leifeld 2013): actors × concepts × stances coded from textDiscourse networks were coded by trained annotators; TXT2KG does it with an LLM. The validity question (does the extracted triple mean what the text meant?) is identical to inter-coder reliability.
Bridge idea

Run TXT2KG on a set of tweets to extract (actor, stance/action, target) triples, then run GraphRAG's Leiden step at three resolutions. Ask the same ten analyst questions at each resolution and score the answers. You will have measured, with a classical SNA parameter, how community-detection choices change what an LLM pipeline reports, a question almost nobody in the GraphRAG literature has asked.

Go deeper in the SNA course. The twelve-unit course on social network analysis in this repository gives the classic side of this lecture in full, with labs and real-data analyses: Unit 12 · The new frontier: data, platforms & LLM agents (LLMs and GNNs together).

Connecting to your research

For SNA and neuro-symbolic work
  • TXT2KG on tweets: extract (actor, stance/action, target) triples from Persian/English tweets with an LLM, build a discourse KG, and answer multi-hop questions ("which accounts amplified claims originating from X about Y?") with G-Retriever.
  • GraphRAG + community detection (Microsoft's variant) is literally SNA inside an LLM pipeline — a bridge you're unusually well placed to study (e.g. how community-detection choices change what the LLM "knows").
  • Text-attributed social graphs: users with bios and posts are TAGs; GLEM-style co-training is a strong approach for stance or bot detection with few labels.

Frontier 2025–26: what changed since the slides

ICLR 2026 oral"LLMs as code generators achieve the strongest overall performance on graph data" — Finkelshtein, Cucerzan, Jauhar & White (Microsoft): the arc from graph-as-prose (2023) to graph-as-tokens (2024) to graph-as-environment (2025–26). The neural model plans; the program does the exact combinatorics. The surprise: "all interaction strategies remain effective on heterophilic graphs".sources: arXiv:2509.18487
ICLR 2026GraphRAG-Bench: when to use graphs in RAG — Graphs help multi-hop reasoning (HippoRAG2 53.4 vs plain RAG 42.9) and hurt simple fact retrieval (49.3 vs 60.9), with token costs differing by more than two orders of magnitude. A NeurIPS 2025 spotlight asks whether KG-based RAG retrieves what you need at all.sources: arXiv:2506.05690
ICML 2026Graph-R1: agentic retrieval over a hypergraph, trained end to end with RL — The 2025–26 turn: RL fine-tuning on graph problems (G1, Graph-R1) mirrors the reasoning-model wave. Caveat from the atlas: "Graph-R1" names at least two different 2025 systems.sources: arXiv:2507.21892
ICLR 2026 oralCRV: chain-of-thought errors from attribution-graph structure — Graphs as a lens on LLM internals: verifying reasoning via its computational graph, editing single features to fix faulty reasoning. The LLM-graph cluster now runs in both directions.sources: arXiv:2510.09312
NeurIPS 2025 spotlightsGraphMaster, KARMA — LLM agents synthesise graphs in data-limited settings and enrich knowledge graphs with multi-agent pipelines; TXT2KG in this lecture is the PyG version of the same construction step. Benchmark leakage (LLMs pre-trained on Cora and arXiv text) is often raised, rarely measured.sources: arXiv:2502.06472
Open question to carryWhen does an LLM actually use graph structure, versus pattern-matching on the text around it? And is GNN encoding into soft prompts better than giving a good LLM the retrieved subgraph as text? The answer seems to depend on model size and hop count, a clean experiment for a project.
Frontiers · from reading graphs to acting on them · KGs became the LLM's memory · graphs help multi-hop, hurt lookups

Words & phrases

TermSimple meaningPersianIn context
hallucinationn.(AI) a fluent, confident output that is false or unsupportedتوهم (در مدل زبانی)"prone to hallucination out of distribution"
pseudo-labeln.a label predicted by a model and then used as if it were a training labelبرچسب کاذب (شبه‌برچسب)"using the GNN's predictions as pseudo-labels"
retrievaln.finding the pieces of stored information relevant to a queryبازیابی"graph-based retrieval of facts"
groundingn.tying a model's answer to given evidenceمستندسازی (اتکا به شواهد)"grounding the LLM in retrieved facts"
Steiner treen.the cheapest tree that connects a given set of nodesدرخت اشتاینر"the Steiner tree of the seed entities"
multi-hopadj.needing several linked facts in a chainچندگامی"multi-hop questions favour GraphRAG"

Go deeper

  • Next: Lecture 17 — agents + graphs: when the LLM acts, plans and uses tools, graphs become memory, plans and interaction structures.
  • Survey: Pan et al. (2024), "Unifying Large Language Models and Knowledge Graphs: A Roadmap" (IEEE TKDE).
  • Open question: is GNN encoding into soft prompts better than simply giving a good LLM the retrieved subgraph as text? The answer seems to depend on model size and hop count — a clean experiment for a project.