CS224W

Lecture 12 · Thu 10/29 · slides PDF · lecture notes

Relational Deep Learning

Most of the world's valuable data sits in relational databases; treat every row as a node and every foreign key as an edge, and a temporal GNN learns the features that data scientists spend months hand-engineering.

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

Before you start: review of the earlier sessions

The thread so far. Sessions 9–11 built heterogeneous models; session 12 points them at the most common data in industry, the relational database, and takes the training pipeline of session 5 seriously about time.

What this session takes from earlier ones

  • Lecture 9: heterogeneous GNNs: the relational GNN is R-GCN/HGT on the database graph
  • Lecture 5: temporal splits: the time-leakage problem is a splitting problem
  • Lecture 4: pre-processing MLPs: each table row needs an encoder for its columns

Those sessions in one minute each

Lecture 11 · GNNs for Recommender Systems

Collaborative filtering is diffusion on the user–item graph: LightGCN keeps only learnable embeddings and parameter-free normalised propagation, and a personalised ranking loss (BPR) aligns training with per-user Recall@K.

\[ E_{\text{final}}=\frac{1}{K+1}\sum_{k=0}^{K}\tilde A^kE,\qquad \text{score}(u,v)=\mathbf z_u^\top\mathbf z_v,\qquad \mathcal L_{BPR}=-\log\sigma(s_{u,v^+}-s_{u,v^-}) \]

Lecture 9 · Heterogeneous Graphs

Treat each relation type (source type, edge type, target type) as its own channel of messages, aggregate within and then across channels — and share or factorise weights so the parameter count doesn't grow with every new relation.

\[ \mathbf{W}_r=\sum_{b=1}^{B}a_{rb}\,\mathbf{V}_b \qquad\text{(basis decomposition: } |R|\cdot B \text{ scalars} + B \text{ shared matrices)} \]

Lecture 5 · GNN Augmentation and Training

Choose the computation graph deliberately (features, virtual nodes, sampling), pick the head that matches the task level, and split so that information from validation/test can never leak into training through message passing.

\[ \hat y_v=\mathbf{W}^{(H)}\mathbf{h}_v^{(L)},\qquad \hat y_{uv}=\mathbf{h}_u^{(L)\top}\mathbf{h}_v^{(L)},\qquad \hat y_G=\text{Pool}\big(\{\mathbf{h}_v^{(L)}:v\in G\}\big) \]

Lecture 4 · A General Perspective on GNNs

A GNN layer is "message, then order-free aggregation (including yourself)"; architectures differ in how neighbours are weighted, and depth must be matched to the receptive field you need because too many layers smooth everything into one vector.

\[ \alpha_{vu}=\frac{\exp(e_{vu})}{\sum_{k\in N(v)}\exp(e_{vk})},\qquad \mathbf{h}_v^{(l)}=\sigma\Big(\sum_{u\in N(v)}\alpha_{vu}\,\mathbf{W}^{(l)}\mathbf{h}_u^{(l-1)}\Big) \]

GCN is the special case \(\alpha_{vu}=1/|N(v)|\) (fixed); GAT learns \(e_{vu}=a(\mathbf{W}\mathbf{h}_u,\mathbf{W}\mathbf{h}_v)\).

Warm-up: answer these before you read on

Why is the binary cross-entropy loss a poor fit for Recall@K? from Lecture 11

It compares every positive against every negative across all users, while the metric is per user; a user with easy positives can dominate the loss.

Why can one-hot node types fail as a substitute for a heterogeneous model? from Lecture 9

When node types have different feature dimensions, or when the same message operator cannot express that "writes" and "cites" should transform the neighbour differently.

When would you add a virtual node? from Lecture 5

When the graph is too sparse for messages to travel, e.g. long chains; the virtual node connects to everything, so any two nodes are two hops apart.

Where does GAT put its parameters that GCN does not have? from Lecture 4

In the attention mechanism: a learned function of the pair (node, neighbour) that produces the aggregation weights, instead of fixed degree-based weights.

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

In short

Commerce, finance, healthcare and social platforms store their data in relational databases: many tables (users, transactions, products…) linked by primary/foreign keys. The questions businesses ask are predictive: Will this user churn in 90 days? What will this product sell next month? Will this patient be readmitted?

Today's answer is slow: flatten the database into one table with hand-made aggregate features (SUM of purchases over 30 days…), then run XGBoost. That takes months of ETL and feature work, throws information away, and risks time leakage. LLMs aren't a fix: databases aren't sequences, LLMs aren't trained to forecast, and context is limited.

Relational Deep Learning (RDL) skips the flattening. Build a relational entity graph — rows are nodes, primary–foreign key matches are edges — attach a training table of (entity, time, label), and train a heterogeneous, time-aware GNN end-to-end. A GNN layer is a learnable SQL JOIN + GROUP BY aggregation. On RelBench, a GNN matched an expert data scientist's 12 hours of feature engineering with under 1 hour of work.

The picture: from database to prediction

Relational Deep Learning pipeline UsersSalesProducts user_id (PK)sale_id (PK)user_id (FK)product_id (FK)value, timeproduct_id (PK) 1 relational entity graph rows → nodes · PK–FK → edges 2 training table user · time · labelu1 · May'23 · churnu1 · Jun'23 · active 3 temporal hetero GNN label time t usehidden 4 P(churn in 30d)= 0.82 5

How to read it (hover a step)

  1. A database: tables of entities with a primary key (PK) and optional foreign keys (FK). The schema graph shows which tables link.
  2. The relational entity graph: one node per row of every table; an edge whenever a FK matches a PK. It's heterogeneous (one node type per table) and nodes have features (unlike plain KGs).
  3. The training table attaches labels with timestamps to entities: (entity ID, time, label). The same user can be "churn" in May and "active" in June.
  4. A heterogeneous GNN whose computation graph is time-dependent: for a label at time \(t\), only rows with timestamp ≤ \(t\) may be sampled — no leakage.
  5. The output is the prediction for that entity at that time (node-level here; link-level for recommendations).

1 · Why: the cost of flattening databases

Typical predictive tasks: which products will a user buy in 7 days; will an active user churn in 90 days; total sales per product next month; loan outcome; hospital readmission; risk to life in the next 24 h. Building such models today takes 6–12 months for a team: data cleaning, target-label engineering, feature engineering, architecture search, MLOps.

The impedance mismatch: ML wants one table; the data is many tables. So engineers invent features — "#monthly sales", "sum of weekly item price", "#orders relative to Sunday" — chosen arbitrarily, using a limited slice of the data, with point-in-time correctness issues.

Feature engineering: arbitrary, lossy, leakage-prone. slide 12 ↗
Why might tabular deep learning have failed to beat gradient-boosted trees, and why might RDL be different?

The slides' hypothesis: a single training table already contains features engineered from other tables, so the information deep learning could exploit is gone before it starts. Trees excel at exactly such hand-made, heterogeneous columns. RDL changes the input: it sees the raw multi-table structure, where deep models can learn their own aggregations — the same reason CNNs beat hand-crafted SIFT features on raw pixels.

Related work: tabular ML (great on one table, but most data isn't one table); Statistical Relational Learning (Friedman et al. 1999, probabilistic relational models) learned graphical models over relational structure, but handled only categorical variables and didn't scale. RDL is a scalable, expressive inheritor of SRL.

Why not LLMs? slide 17 ↗

2 · A database is a graph

Formally: a database is a set of tables \(\mathcal T=\{T_1,\dots,T_n\}\) with links \(\mathcal L\subseteq\mathcal T\times\mathcal T\). Each table is a set of entities with a PK and optional FKs. The relational entity graph has node set \(\mathcal V=\bigcup_{T\in\mathcal T}T\) (all rows) and an edge between \(v_1,v_2\) whenever their primary and foreign keys match.

Schema graph: the high-level structure. slide 35 ↗

Then ML on databases is ML on graphs: node-level (churn, lifetime value, next best action), link-level (product affinity, recommendations), graph-level (fraud, money laundering).

Relational entity graph: rows connected via PK–FK. slide 37 ↗

3 · Defining predictive tasks: the training table

Most tasks are temporal: a customer's label changes over time, and the database changes over time, so features must be recomputed for every time point. To define a task you need an entity, a label and a time.

The training table: rows (entity ID, timestamp, label). Classification, regression or multi-class. The time column is essential: an entity may have different labels at different times, and only information up to the label time may be used.

Training labels with timestamps attached to the graph. slide 48 ↗

Example: predict whether a user churns (zero sales) in the next 30 days → training table (user, time, churn label), attached to the entity graph.

4 · Relational GNNs: learnable joins and aggregations

Each node's neighbourhood defines its computation graph; nodes learn how to use their neighbours. What's new is time: the computation graph, message + aggregation, and neighbour sampling are all time-dependent.

GNN features vs hand-engineered features. slide 53 ↗

GNN layer = SQL JOIN + aggregation

An inner join \(R\bowtie S=\{r\cup s : r\in R, s\in S, r.\text{pkey}=s.\text{fkey}\}\) is exactly the set of PK–FK edges: \(a_{ij}=1\) iff \(r_i.\text{pkey}=s_j.\text{fkey}\). A GNN layer aggregates over those edges with a learnable function, a temporal embedding and a fact representation:

A GNN performs a JOIN + AGG. slide 56 ↗
\[ \mathbf h_{\text{user}}=\bigoplus_{w\in N(\text{user})}\big(\mathbf t(t_w)\cdot\mathbf x_w\big)\quad\longleftrightarrow\quad \texttt{SELECT SUM(VALUE) FROM SALES WHERE DATE>... GROUP BY USER\_ID} \]

Why GNNs beat hand features here

  • They learn how to aggregate: drop irrelevant neighbours, detect fine-grained patterns (buying behaviour over the last year).
  • They exchange information across training examples: users with similar products or behaviour inform each other.
  • Multi-hop reasoning across table boundaries (user → purchases → products → other buyers) captures information hard to pre-compute.
  • First-class temporal support: temporal embeddings for relative and seasonal patterns; leakage prevented by temporal sampling directly in the data loader.
  • Temporal sampling: nodes after the label time are not available. slide 60 ↗

5 · RelBench and GNN vs expert data scientist

RelBench (relbench.stanford.edu): 7 datasets (e-commerce: rel-amazon, rel-avito, rel-hm; social: rel-event, rel-stack; sports: rel-f1; medical: rel-trial) with 3–15 tables, 74K–41M rows, 15–140 columns, time spans from 2 weeks to 55 years; 30 tasks of entity classification, entity regression and recommendation. It downloads data, loads task tables, enforces a standardised temporal evaluation, and integrates with PyG and PyTorch Frame (for encoding table columns).

7 datasets with rich schemas, 30 real-world tasks. slide 66 ↗

The user study

Results: GNN vs expert data scientist vs naive baseline. slide 85 ↗

Task (rel-stack): will a user be active in the next 6 months? An experienced data scientist (5 years in industry) followed the full workflow: exploratory data analysis (4 h; e.g. activity is seasonal, comments follow a power law), feature ideation (0.5 h), SQL writing (5 h, hundreds of lines), XGBoost sweep (2 h), SHAP analysis (1 h) → ~12 hours of expert work, ~682 lines of code. The RDL model: <1 hour of manual work, 54 lines of code, similar training time — and equal or better ROC-AUC, across several RelBench tasks.

The mathematics, step by step

Relational deep learning has almost no new formulas: it is a recipe for turning a database into a graph on which the layers of Lectures 3 to 9 run. What must be exact is the bookkeeping: what a node is, what an edge is, and which rows a prediction made at time \(t\) is allowed to see.

Symbols used in this session

symbolmeaningwhat kind of object
\(\mathcal T\)the set of tables of the databaseset of tables
\(\mathcal V,\ \mathcal E\)nodes (one per row) and edges (one per primary-key–foreign-key link)sets
\(v.\text{pkey},\ v.\text{fkey}\)primary key of row \(v\); a foreign-key value stored in row \(v\)identifiers
\(t_v\)timestamp of row \(v\) (when the row came into existence)time
\(t\)seed time: the moment at which a prediction is madetime
\(N_{\le t}(v)\)neighbours of \(v\) whose timestamp is at most \(t\)set of rows
\(\mathbf h_v^{(t)}\)embedding of row \(v\) computed for a prediction at time \(t\)vector
\(\bigoplus\)an order-free aggregation: sum, mean, max, countoperation
\(y(v,t)\)training label of entity \(v\) at seed time \(t\), computed from rows after \(t\)number or class

1A database as a graph

\[ \mathcal V=\bigcup_{T\in\mathcal T}T,\qquad (v_1,v_2)\in\mathcal E\iff v_1.\text{pkey}=v_2.\text{fkey} \]

In words. Every row of every table becomes a node; the node's type is its table. Two rows are joined by an edge exactly when one of them stores the other's primary key as a foreign key.

Why it has this form. A foreign key is already a pointer from one row to another, so the edges are read off the schema with no modelling decisions. The result is a heterogeneous graph in the sense of Lecture 9: node types are tables, edge types are foreign-key columns (plus their reverses). The remaining columns of a row become its node features, encoded per data type (numbers, categories, text, timestamps).

With numbers. Tables Customers (2 rows), Products (3 rows), Orders (4 rows); each order row holds one customer id and one product id. The graph has \(2+3+4=9\) nodes and \(4\cdot2=8\) edges (each order points to one customer and one product). Two customers who bought the same product are 4 hops apart: customer – order – product – order – customer.

Watch out. An order is a node here, not an edge. Tables that only link two others (junction tables) add a hop to every path through them; Lecture 13 returns to this.

2Message passing that respects time

\[ \mathbf h_v^{(t)}=\text{UPD}\Big(\mathbf x_v,\ \bigoplus_{w\in N_{\le t}(v)}\text{MSG}\big(\mathbf h_w^{(t)}\big)\Big),\qquad N_{\le t}(v)=\{w\in N(v):t_w\le t\} \]

In words. When predicting at time \(t\), a row may only receive messages from rows that already existed at time \(t\). Later rows are removed from the neighbourhood before aggregating.

Why it has this form. The label is something that happens after \(t\). If rows created after \(t\) took part in message passing, the model would see the future it is asked to predict, score well in training and fail in deployment (temporal leakage). The filter is applied at every hop of neighbour sampling, with the same \(t\), so the whole computation graph is a snapshot of the database as it was at the seed time. The same entity therefore has different embeddings at different seed times.

With numbers. A customer has orders on day 1 (amount 10), day 5 (20) and day 9 (30). Seed time day 6: \(N_{\le6}\) contains the first two; sum \(=30\), count \(=2\), mean \(=15\). Using all three would give a sum of 60 and would hand the model an order from the future.

Watch out. The comparison must be \(\le t\) for every sampled row, including rows two or three hops away; filtering only the first hop still leaks through the second.

3Aggregation is a learned GROUP BY

\[ \mathbf h_{\text{user}}=\bigoplus_{w\in N(\text{user})}\big(\mathbf t(t_w)\cdot\mathbf x_w\big)\quad\longleftrightarrow\quad \texttt{SELECT SUM(VALUE) FROM SALES WHERE DATE>... GROUP BY USER\_ID} \]

In words. Summing the neighbours' features of a user node is the same computation as an SQL query that groups the sales table by user and sums a column. A GNN layer is that query with learned weights; two layers are a query over two joins.

Why it has this form. A hand-made feature such as 'total spend in the last 30 days' is a join along a foreign key, a filter on time and an aggregation. In the graph, the join is the edge, the filter is a weight \(\mathbf t(t_w)\) that depends on the row's time, and the aggregation is \(\bigoplus\). The GNN keeps this structure but learns which columns, which time window and which combination to use, and stacking layers composes joins that a feature engineer would have to write by hand.

With numbers. Sales of one user: values \(10,20,30\) on days \(1,5,9\); seed time day 10; a hard window of the last 6 days is \(\mathbf t=0,1,1\). Aggregate: \(0\cdot10+1\cdot20+1\cdot30=50\), the answer of the SQL query with DATE > 4. A learned, soft window might weight them \(0.1,0.6,1.0\) and give \(43\).

Watch out. The correspondence is for sum, mean, max and count. Queries with exact thresholds or distinct counts are not reproduced exactly by smooth aggregations, which is one place where hand-made features can still win.

4The training table

\[ \mathcal D_{\text{train}}=\big\{(v,\ t,\ y(v,t))\big\},\qquad y(v,t)=\text{AGG}\big\{x_w:\ w \text{ linked to } v,\ t<t_w\le t+\Delta\big\} \]

In words. A predictive task is a table of (entity, seed time, label). The label is computed by a query over the rows that appear in a window of length \(\Delta\) after the seed time.

Why it has this form. The database has no label column for 'will this customer buy next month'; the label is manufactured from history. Choose a past seed time \(t\), look only at what happened in \((t,t+\Delta]\), and record the answer. Repeating this for many seed times gives many training examples per entity. The input side uses rows up to \(t\) (card 2), the label side rows after \(t\): the two never overlap. Train, validation and test sets are separated by seed time, in that order, never at random.

With numbers. Task: total spend in the next 7 days. The customer above, seed time day 2: orders in \((2,9]\) are days 5 and 9, label \(50\). Seed time day 6: only day 9, label \(30\). Seed time day 9: nothing after it, label \(0\). Three training rows from one customer.

Watch out. If the validation seed time lies inside a training label window, the two share rows; windows must not straddle the split points.

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: in slide 28, is "a user bought a product" an edge or a node? show answer

It is a node (the Sales row), with two edges. Sales rows carry their own attributes (price, time), which is why they are entities and not just edges.

from A database is a graph

Check yourself: why is a KG from Lecture 10 different? show answer

A KG node is usually just an ID with typed edges; all information is in the edges. In a relational entity graph, much of the information is in the node features, and edges only express key references.

from The relational entity graph

Check yourself: which SQL feature would need two GNN layers? show answer

Anything that crosses two joins, e.g. "average price of the products in the user's purchases": user ← sales ← products.

from SQL joins are graph edges; a GNN layer is JOIN + AGG

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. Deep learning's revolution, and where the data really is
  2. Predictive questions on databases, and why answering them is slow
  3. The key question, and why not just use an LLM
  4. What Relational Deep Learning (RDL) is
  5. A database is a graph
  6. Tables, keys and the schema graph
  7. The relational entity graph
  8. Defining a task: the training table
  9. Attaching labels to the entity graph
  10. Relational GNNs: time-dependent computation graphs
  11. SQL joins are graph edges; a GNN layer is JOIN + AGG
  12. Benefits of GNNs on relational data
  13. The RDL paper and the RelBench benchmark
  14. Case study: an expert data scientist's workflow
  15. Results: GNN vs the expert

Deep learning's revolution, and where the data really is slides 4-7 ↗

Slides 4–7: deep learning conquered sequences and grids; most valuable data sits in relational databases. slides 4-7 ↗

Slide 4 recalls the deep learning revolution: huge progress on sequences (text, shown as a document) and images (photos, generated images). Slide 5: these breakthroughs are fueled by Transformers (the architecture diagram next to a chart of ChatGPT's exam results). Slide 6: they are also fueled by data; the cover of The Economist reads "The world's most valuable resource: data and the new rules of competition".

Slide 7 points out where most of an organisation's valuable data actually lives: in relational databases. The three pictures are database schemas from commerce, finance and social media: boxes (tables) with lists of columns, connected by lines (key relationships).

The tension of the whole lecture is here. Deep learning won on sequences and grids. Enterprise data is neither: it is many tables linked by keys. Can deep learning work on that data directly?

Predictive questions on databases, and why answering them is slow slides 8-12 ↗

Slides 8–12: predictive questions live across tables, but ML wants one table; the impedance mismatch is resolved by slow, lossy, leakage-prone feature engineering. slides 8-12 ↗

Slides 8–10 list typical predictive tasks on relational data, each next to a schema picture:

  • Commerce (slide 8; schema with Users, Sales and Products tables): Which products will a user purchase in the next 7 days? Will an active user churn in the next 90 days? What will be the total sales for each product in the next 30 days?
  • Finance (slide 9): What will the loan outcome be (good vs bad)? What will the total number of failed loans be in the next year?
  • Healthcare (slide 10): Will a patient return if discharged from the hospital? Which hospital admissions have the greatest risk to life in the next 24 hours?

Note that almost all are about the future ("in the next N days").

Slide 11, "building AI is slow and complex". The standard pipeline has five stages: input data cleaning and curation → target label engineering → feature engineering → architecture and hyperparameter search → ML Ops. It takes 6–12 months for a team of data scientists, data engineers and product engineers.

Slide 12, the impedance mismatch. Goal: learn a user churn model from sales, purchased products and browsing behaviour. The data is several tables (Users, Sales, Products, Sessions, Views). Standard ML wants one table: one row per example (user) and columns of features such as "#monthly sales", "sum of weekly item price", "#orders relative to Sunday", plus a label column. Turning many tables into this one table creates three problems:

  • Features are chosen arbitrarily (which aggregations? which time windows?).
  • Only a limited set of the data is used.
  • Issues with point-in-time correctness / information leakage: a feature computed at the wrong time can contain information from after the prediction time.

The key question, and why not just use an LLM slides 13-17,19 ↗

Slides 14–19: the LLM route serialises a database neighbourhood into a prompt, and why that does not fit the problem. slides 14-19 ↗

Slide 13 asks the key question: how can we use the data without the longest tasks (extraction, transformation, loading: ETL)? We want ML algorithms that process data in its natural form.

Slide 14: why not use an LLM? Slide 15, "Some have tried": Figure 1 of the paper "Tackling prediction tasks in relational databases with LLMs" (Wydmuch, Borchmann, Graliński; Snowflake AI Research). To build one LLM example, start from the Task Table row (target, timestamp, customer ID), follow the keys to the Customers, Transactions and Products rows, and serialise everything into one nested JSON document (customer name and address, a list of transactions, each with product name, description and weight), ending with "Target": 1. Slide 16, "Prompt": what such a prompt looks like for a real retail database, a full slide of dense JSON text (product groups, colours, timestamps, prices, …) for a single example.

Slide 17, why not LLMs:

  • LLMs are not trained to understand and learn from the relational nature of databases.
  • Database prediction is not sequence modelling: there is no natural order of rows, and serialising destroys the structure.
  • LLMs are not trained to predict the future; most database tasks are forecasts.
  • Context size is limited: slide 16 shows how quickly one user's history fills the prompt.

Slide 19, modern ML: we want deep learning models that operate on relational tables, but the deep learning toolbox is designed for other input types: text (sequences), images (grids), and the picture of a crowd of people suggests sets/graphs. Relational tables need their own architecture.

What Relational Deep Learning (RDL) is slides 21-25 ↗

Slides 21–25: the definition, promise and lineage of Relational Deep Learning. slides 21-25 ↗

Slide 21: a picture of linked tables → "Relational Deep Learning" (a neural network) → prediction.

Slide 22, definition. RDL is:

  • End-to-end deep learning on relational tables (databases).
  • It works directly on the tables, with no transformations and no feature engineering.
  • It casts predictive tasks as graph representation learning problems.

Slide 23, impact and consequences:

  • More accurate models (no feature engineering, so no information thrown away).
  • More robust models (model-learned features automatically "update" over time).
  • Shorter time to model (no mundane ETL work).
  • Simpler infrastructure (no pipelines, no feature stores, etc.).

Slide 24, related work 1: tabular ML (the figure is a decision tree). It is great for building models on one table, but most data is not a single table. And on tabular data deep learning is not dominant (gradient-boosted trees usually win). The slide's hypothesis: a single table already contains features engineered from other tables, so information is lost before the model starts. RDL models the relations between multiple tables, unlike tabular ML.

Slide 25, related work 2: Statistical Relational Learning [Friedman et al., 1999]. It learns a distribution (a graphical model) over the relational structure; the figure shows a probabilistic relational model with Movie, Actor and "Appears" boxes, with arrows for relationships and probabilistic dependencies. Predictions come from a world model plus inductive logic programming. Its limits: it only works with categorical variables and does not scale to large data. RDL is a scalable, expressive inheritor of statistical relational learning.

For a neuro-symbolic reader: SRL is the symbolic ancestor (explicit probabilistic structure over relations, logic-based inference); RDL keeps the relational structure but replaces the hand-specified dependencies with learned message passing.

A database is a graph slides 27-30 ↗

Slides 27–30: the Users–Sales–Products schema and the graph it becomes; every ML question becomes a node-, link- or graph-level task. slides 27-30 ↗

Slide 27, insight: data is a graph. The figure is a small schema: a Users table (ID), a Sales table (ID, Product_ID, Session_ID, User_ID, Price) and a Products table (Product_ID). Sales points to Users and to Products through keys.

Slide 28 draws the same data as a graph: users on the left, sales in the middle (each sale node shows its price: $20, $80, $15, $20, $80, $80, $15), products on the right (a T-shirt, sneakers, sunglasses). Each sale connects one user to one product. The arrow from schema to picture is the whole idea: rows become nodes, key references become edges.

Slide 29: once the database is a graph, familiar graph ML tasks appear:

  • Node-level: churn, lifetime value, next best action.
  • Link-level: product affinity, recommendations.
  • Graph-level: fraud, money laundering.

Slide 30, the graph ML problem-solving pipeline: Relational DB → Graph problem (users–sales–products graph) → Graph ML (a neural network passing messages over a computation graph) → Solutions (the same graph with predicted labels such as "Churn"/"Active" attached to users).

Check yourself: in slide 28, is "a user bought a product" an edge or a node? show answer

It is a node (the Sales row), with two edges. Sales rows carry their own attributes (price, time), which is why they are entities and not just edges.

Tables, keys and the schema graph slides 32-36 ↗

Slides 32–36: a transaction row and the rows it points to, and the schema graph that summarises which tables link to which. slides 32-36 ↗

Slide 32: real-world data is stored in databases. A transaction (a user buying a product) is stored as a row of a Transaction table with columns Trans ID, User ID, Product ID, Value, Timestamp (one highlighted row: transaction 100, user 51, product 345, value $1000, timestamp 1710281001).

Slide 33: databases are often relational. The User ID in the transaction row points to a row in the User table (User ID, Gender, e.g. 51, Male), and the Product ID points to a row in the Product table (Product ID, Category, e.g. 345, Bike). So relational databases can be seen as heterogeneous graphs.

Slide 34, mathematically:

  • A database is a set of tables \(\mathcal T=\{T_1,\dots,T_n\}\).
  • Links between tables are \(\mathcal L\subseteq\mathcal T\times\mathcal T\).

Slide 35: the schema graph represents the high-level structure of the heterogeneous graph. Its nodes are tables, not rows. The example has three tables: Products (ProductID, Description, Image, Size), Transactions (TransactionID, ProductID, Timestamp, CustomerID, Price) and Customers (CustomerID, Name), with edges "Bought which" (Transactions–Products) and "Bought by" (Transactions–Customers).

Slide 36: real schema graphs can be much more complex; the picture is an industrial schema with dozens of tables and many links.

In Lecture 9 terms: the schema graph plays the role of the metagraph (node types and relation types); the relational entity graph (next block) is the actual heterogeneous graph.

The relational entity graph slides 37-39 ↗

Slides 37–39, the relational entity graph: one node per row, one edge per matching primary–foreign key pair. slides 37-39 ↗

Slide 37, the relational entity graph: create connections via primary–foreign keys. The figure repeats the schema (Users, Sales, Products) and, below it, the users–sales–products graph.

Slide 38, the formal definition. Given a database of tables \(\mathcal T=\{T_1,\dots,T_n\}\) and relations \(\mathcal L\subseteq\mathcal T\times\mathcal T\):

  • Each table is a set of entities \(v\in T_i\). Each entity has a primary key (its unique ID) and optional foreign keys (IDs of rows in other tables).
  • The node set is all rows of all tables: \(\mathcal V=\bigcup_{T\in\mathcal T}T\).
  • The edge set connects two entities \(v_1,v_2\) whenever the primary key of one matches a foreign key of the other.

Slide 39: entities also have features, unlike knowledge graphs. The tables show it: a transaction has a value and a timestamp, a user has a gender, a product has a category. These columns become node features (numbers, categories, text, timestamps).

Check yourself: why is a KG from Lecture 10 different? show answer

A KG node is usually just an ID with typed edges; all information is in the edges. In a relational entity graph, much of the information is in the node features, and edges only express key references.

Defining a task: the training table slides 41-45 ↗

Slides 41–45: the three-step approach and the training table (entity, time, label) that defines a temporal task such as churn in the next 30 days. slides 41-45 ↗

Slide 41, overview of the approach: (a) define tasks (e.g., "how much will each customer buy in the next 90 days?"), (b) training table generation (gather training targets from historical data), (c) link the training table to the relational tables. Next: define tasks, then the RDL model.

Slide 42, example: predict whether a user will churn in the next 30 days. Most tasks are temporal:

  • a customer's label changes over time;
  • the database changes over time;
  • so for every time point, any feature must be recomputed.

To define a task you need three things: an entity, a label and a time. The side note: temporal tasks are especially challenging because features are time-dependent (recompute for every time) and an entity's label can change between time steps.

Slide 43, the training table: a special table that holds the training labels as rows (entity ID, time, label).

  • It supports classification, regression and multi-class tasks.
  • The time column is essential for temporal prediction.
  • An entity may have different labels at different times.
  • Only information up to the time of the label may be used.

Slide 44 shows a small training table with columns Entity ID, Timestamp, Label: rows such as entity 99 at time 10172024 with label 1 and entity 100 with label 0.

Slide 45, the churn example. The schema is Users, Sales, Products. Task: predict whether a user is going to churn, where churn means zero sales in the next 30 days. Training table: (user, time, churn label).

Notice how the label itself is computed from the database: for a user \(u\) and time \(t\), look at Sales rows of \(u\) with timestamps in \((t, t+30\text{ days}]\). The features may only use rows with timestamp \(\le t\). This is how a training table can be generated automatically from history.

Attaching labels to the entity graph slides 46-48 ↗

Slide 48: each user carries time-stamped labels; a GNN is trained on the graph with them. slides 46-48 ↗

Slide 46 is the full RDL pipeline in four panels (from the RDL paper):

  1. (a) Relational tables with a training table. Products (Product_ID, Description, Image, Size), Transactions (Transaction_ID, Product_ID, Timestamp, Customer_ID, Price), Customers (Customer_ID, Name), and the training table Customer LTV (90-day LTV, User_ID, SeedTime), which points to Customers.
  2. (b) Entities linked by foreign keys: individual rows of each table connected through their keys.
  3. (c) Relational entity graph: products 1, 2, 3 connect to transactions, transactions to customers, and customers to training-table rows (labels A and B).
  4. (d) Graph neural network: for each training row (A, B), the computation tree unrolled from the entity graph: label node ← customer ← transactions ← products and other customers.

Slide 47 repeats the relational entity graph (create connections via primary–foreign keys).

Slide 48: the training labels, together with their timestamps, are attached to the graph. Each user gets label nodes, one per (time, label): for example the first user has "May '23: Churn" and "June '23: Active"; another user has "April '23: Active", "May '23: Churn", "June '23: Active". The same user is a training example several times, at different times, with different labels.

Relational GNNs: time-dependent computation graphs slides 50-53 ↗

Slides 50–53: a GNN on the entity graph unrolls a different tree for each label time, so no future information leaks in. slides 50-53 ↗

Slide 50 repeats the four-panel pipeline as the start of the "Relational GNN" section.

Slide 51, a GNN on the entity graph. A node's neighbourhood defines its computation graph. Nodes learn how to optimally use information from neighbours to get better representations. The figure: on the left the entity graph (users, sales, products) with one user highlighted; on the right two GNN computation graphs for the same user, one for the label "May '23 Churn" and one for "June '23 Active". The two trees differ, because each one may only use sales that happened before its own time.

Slide 52, GNNs on temporal graphs, with three panels:

  1. (a) Schema graph: Products, Transactions, Customers with "Bought which" and "Bought by".
  2. (b) Relational entity graph laid out along a time axis from 0 to 6: transactions \(v_1,\dots,v_6\), products \(v_7,v_8,v_9\), customers \(v_{10},v_{11},v_{12}\).
  3. (c) Computation graphs of customer \(v_{11}\) at different times: at \(t=1\) it sees only transaction \(v_1\) (and product \(v_7\)); at \(t=3\) it sees \(v_3,v_1\) (products \(v_8,v_7\)); at \(t=5\) it sees \(v_1,v_3,v_5\) (products \(v_7,v_8,v_9\)).

So in RDL:

  • the computation graph for each node is time-dependent;
  • message + aggregation become time-dependent;
  • sampling over neighbours is time-dependent.

Slide 53, GNN vs feature engineering. GNN-based features: a user aggregates learned messages from the sales of a T-shirt and sneakers. Hand-engineered features: columns like SUM(TRANSACTIONS.Price) over (-30, 0) days, AVG(TRANSACTIONS.Price) over (-30, 0) days, … Key message: GNN aggregation is a learnable version of hand-crafted features, and GNNs perform better because they learn the optimal features.

SQL joins are graph edges; a GNN layer is JOIN + AGG slides 54-56 ↗

Slides 54–56: an inner join keeps the key-matching pairs, which are the graph edges; a GNN layer is a learnable JOIN + WHERE + aggregation. slides 54-56 ↗

Slide 54 recalls relational algebra:

  • A table \(R\) is a set of entities \(R=\{r_1,\dots,r_n\}\).
  • Each entity is a tuple \(r_i=(r_{i1},r_{i2},\dots,r_{in})\).
  • Given two tables \(R,S\), a join is a subset of the Cartesian product \(R\times S\).
  • Aggregation specifies which rows are kept (and how they are combined).

Example 1, cross join: SELECT * FROM employee INNER JOIN department ON 1=1. The Employee table (Rafferty 31, Jones 33, Heisenberg 33, Robinson 34, Smith 34, Williams NULL) and the Department table (31 Sales, 33 Engineering, 34 Clerical, 35 Marketing) give all \(6\times4=24\) pairs.

Slide 55, example 2, inner join:

\[ R\bowtie S:=\{r\cup s\mid r\in R\wedge s\in S\wedge \text{Fun}(r,s)\},\qquad \text{Fun}(r,s):\ r.\text{pkey}=s.\text{fkey}. \]

The SQL query joins employee and department on DepartmentID. The result keeps only matching pairs: Robinson 34 Clerical, Jones 33 Engineering, Smith 34 Clerical, Heisenberg 33 Engineering, Rafferty 31 Sales (Williams, with NULL, disappears; Marketing has no employee). Now picture \(R\times S\) as a matrix: the pairs kept are exactly the entries

\[ a_{ij}=\begin{cases}1 & \text{if } r_i.\text{pkey}=s_j.\text{fkey}\\ 0 & \text{otherwise.}\end{cases} \]

These are exactly the pkey–fkey edges. The adjacency matrix of the entity graph between two tables is the inner-join indicator matrix.

Slide 56, GNNs perform a JOIN + AGG. Input: a USER_ID table (1, 2, 3) and a SALES table (user 1: 20 on 01-01, 80 on 01-02; user 2: 15 on 01-01; user 3: 20 on 01-02, 80 on 01-03). A GNN can learn the query

SELECT SUM(VALUE) FROM SALES WHERE DATE > 01-01 GROUP BY USER_ID

whose result is user 1: 80, user 2: 0, user 3: 100. The GNN layer that does this is

\[ \bigoplus_{w\in\mathcal N(v)}\mathbf t(t_w)\cdot\mathbf x_w, \]

with a learnable aggregation \(\bigoplus\) (over the sales \(w\) joined to user \(v\): the JOIN), a temporal embedding \(\mathbf t(t_w)\) of the sale's timestamp (which can learn to zero out sales on or before 01-01: the WHERE), and a fact representation \(\mathbf x_w\) (the sale's features, here VALUE). Sum aggregation then gives the SUM … GROUP BY.

Check yourself: which SQL feature would need two GNN layers? show answer

Anything that crosses two joins, e.g. "average price of the products in the user's purchases": user ← sales ← products.

Benefits of GNNs on relational data slides 57-60 ↗

Slides 57–60: the four benefits of GNNs on relational data, including temporal sampling that cannot leak. slides 57-60 ↗

Slide 57: GNNs learn how to aggregate information.

  • They can discard neighbouring information that is irrelevant for the downstream task.
  • They can detect fine-grained patterns in local neighbourhoods (e.g., buying behaviour over the last year).

The figure is a schema with Users, Sales, Products, Sessions and Views tables.

Slide 58: GNNs can exchange information across training examples. Instead of treating examples as isolated rows (as tabular ML does), there is now inter-dependency between entities: users with similar features, users with similar behaviour. A GNN uses this to enrich an entity's representation. The schema figure annotates two such multi-hop questions: "How is the buying behaviour of users that have bought similar products?" and "How is the buying behaviour of users that have looked at similar products?"

Slide 59: multi-hop reasoning across table boundaries catches information that is hard to pre-compute. The figure attaches the training labels to Users and annotates paths: "Which user has bought which product?" (Users → Sales → Products) and "How active was the user in the past?" (Users → Sessions/Views).

Slide 60: first-class temporal support.

  • Capture fine-grained relative and seasonal features via temporal embeddings.
  • Avoid data leakage via temporal sampling directly during data loading.

The figure: a seed node at time \(T\). Its neighbours at time \(T-1\) and earlier (solid arrows) are available for sampling; the node at time \(T+1\) and everything attached to it (dashed) are not available for sampling. Leakage is prevented by construction in the sampler, not by careful feature code.

The RDL paper and the RelBench benchmark slides 61,63-68 ↗

Slides 61–68: the RelBench pipeline, its seven databases and thirty tasks. slides 61-68 ↗

Slide 61: the vision is described in the paper "Relational Deep Learning: Graph Representation Learning on Relational Tables" (Fey, Hu, Huang, Lenssen, Ranjan, Robinson, Ying, You, Leskovec; Stanford, Kumo.AI, Max Planck Institute for Informatics, Yale, UIUC). Available at relbench.stanford.edu.

Slide 63, RelBench enables research on RDL. It is more than a collection of databases. The pipeline figure: RelBench relational databases → RelBench data, task and graph loaders → your RDL model (e.g., PyG) → RelBench evaluator → RelBench leaderboard. Features:

  • Automatically download datasets.
  • Load database and task tables.
  • A standardised evaluation protocol that prevents temporal leakage from the test set.
  • Framework-agnostic data structures: use your favourite ML stack.

Slide 64, PyTorch Frame and PyG integration: load a database as a PyG graph; train a GNN end-to-end; temporal neighbour sampling; use PyTorch Frame to encode the table columns (numerical, categorical, text, timestamp) into node features.

Slide 65, 7 diverse datasets: E-commerce (rel-amazon, rel-avito, rel-hm), Social (rel-event, rel-stack), Sports (rel-f1), Medical (rel-trial).

Slide 66, rich schemas: 3 to 15 tables; 74k to 41M rows per database; 15 to 140 columns per database; time spans from 2 weeks to 55 years. The two example schemas are rel-amazon (review, customer, product tables) and the much larger rel-trial.

Slide 67, 30 real-world predictive tasks of three kinds:

  • Entity classification: rel-amazon user-churn, item-churn; rel-stack user-badge; rel-trial study-outcome; …
  • Entity regression: rel-amazon user-ltv, item-ltv; rel-avito ad-ctr; rel-f1 driver-position; …
  • Recommendation: rel-amazon user-item-purchase; rel-avito user-ad-visit; rel-stack user-post-comment, post-post-related; …

Slide 68: a screenshot of the website (https://relbench.stanford.edu) to get started.

Case study: an expert data scientist's workflow slides 70,72-81 ↗

Slides 70–81: how an experienced data scientist solved one RelBench task by hand, step by step with the time each step took. slides 70-81 ↗

Slide 70: the experiment recruited an experienced data scientist (Alejandro): 5 years in industry, specialising in financial databases, responsible for the full model-building lifecycle.

Slide 72, the representative RelBench task: the Stack Exchange database (schema shown). Question: will a user be active in the next 6 months?

Slides 73–79 build the expert's manual workflow step by step, with time spent:

  1. Exploratory data analysis (EDA), 4 hours. Example observations (slide 75, three histograms): activity is seasonal; comments follow a power law; negative votes are infrequent.
  2. Feature ideation, 0.5 hour. Example features: weeks_since_last_comment, badge_score, location_is_null.
  3. SQL query writing, 5 hours: hundreds of lines of code (slide 77 shows a long SQL script).
  4. XGBoost hyperparameter sweep, 2 hours.
  5. SHAP feature-importance analysis, 1 hour.

Slide 80, the SHAP plot (each row a feature; position = impact on the model output; colour = feature value). Top features: weeks_since_last_comment, badge_score, last_q_weeks_ago, num_posts_commented, last_a_weeks_ago, num_badges, location_is_null, about_me_length, … Selected observations:

  • Website "seniority" is predictive (total number of comments, badge score, etc.).
  • Time since last active / commented is predictive.
  • A completed bio (about me, location, etc.) is predictive.
  • Number of positive/negative votes is not predictive.
  • Interacting with "senior" community members is not predictive.

Slide 81: the final list of features (a long table), about 12 hours of high-quality expert work.

Notice how each feature is a hand-written JOIN + aggregation + time window. "weeks_since_last_comment" is a MAX over the user's comments; "num_posts_commented" a COUNT DISTINCT. These are exactly the operations slide 56 says a GNN layer can learn.

Results: GNN vs the expert slides 83-87 ↗

Slides 83–87: the GNN beats both the naive baseline and the expert on rel-stack (left) and on four more tasks (right: GNN green, expert navy). slides 83-87 ↗

Slide 83, the naive baseline: XGBoost on the users table only, with no feature engineering (columns Id, AccountId, DisplayName, Location, WebsiteUrl, AboutMe, CreationDate). Test ROC-AUC 0.6842.

Slide 84: the expert data scientist reaches test ROC-AUC 0.8643, with 12 hours of manual work, ~682 lines of code and 1 hour of model training (2 days to model). Footnote: work is measured as the marginal effort to solve a new task.

Slide 85: the GNN reaches 0.8945, with under 1 hour of manual work, 54 lines of code and 1 hour of model training.

Slide 86 summarises as four bar charts (GNN vs expert): AUC-ROC 0.90 vs 0.86; hours of human work 1 vs 11; lines of code 54 vs 682; hours of model training 1 vs 1.

Slide 87, more RelBench tasks (AUC-ROC, GNN vs expert): stackex-engage 89.50 vs 86.43; stackex-badges 88.19 vs 86.14; amazon-churn 70.46 vs 67.55; amazon-product-churn 82.98 vs 81.67. The GNN wins on all four.

Reading the results: the accuracy gain (a few AUC points) is real, but the bigger change is the cost: about 10× less human time and over 10× less code. The expert's features are a good but fixed subset of the JOIN+AGG space; the GNN searches that space with gradients.

Not shown (no new content): slides 1,2,3,18,20,26,31,40,49,62,69,71,82 — title page, announcements, section-divider title pages, an exact repeat of slide 13 (slide 18), and a logo-only page (slide 71).

Review: what to keep from this session

Carried forward. Lecture 13 fixes the two weaknesses of plain message passing on database graphs (junction tables and multi-modal rows); Lecture 14 asks for in-context learning over databases.

Quick self-check

What is time leakage and how does the temporal graph prevent it?

Using information from after the prediction time; the neighbourhood of an entity at timestamp t contains only rows with time ≤ t.

Why does a foreign key make a good edge?

It is a deliberate, hand-verified link between two entities; the schema is a graph the database designers already drew.

What replaces the hand-made aggregate features?

The GNN layers: an aggregation over a customer's transactions is exactly a message-passing step over the foreign-key edges.

Key idea

A relational database is a temporal heterogeneous graph; a GNN on that graph is a differentiable, multi-hop generalisation of SQL joins and aggregations, so it can learn predictive features end-to-end while temporal sampling prevents leakage.

\[ \mathcal V=\bigcup_{T\in\mathcal T}T,\qquad (v_1,v_2)\in\mathcal E \iff v_1.\text{pkey}=v_2.\text{fkey},\qquad \mathbf h_v^{(t)}\ \text{uses only rows with time}\le t \]

Worked example: a GNN layer as a SQL query

SALES rows (user, value, date): (1, 20, 01-01), (1, 80, 01-02), (2, 15, 01-01), (3, 20, 01-02), (3, 80, 01-03). Task: features "spend after 01-01" per user.

  1. SQL: SELECT USER_ID, SUM(VALUE) FROM SALES WHERE DATE > '01-01' GROUP BY USER_ID → user 1: 80; user 2: 0; user 3: 100.
  2. GNN view: user nodes receive messages from their sale nodes (PK–FK edges). If the temporal encoding \(\mathbf t(t_w)\) learns ≈0 for 01-01 and ≈1 later, and \(\mathbf x_w\) encodes VALUE, a sum aggregator outputs exactly 80, 0, 100.
  3. But the GNN can also learn weighted, non-linear, multi-hop versions (e.g. "spend on products that churned users also bought") that nobody would think to write in SQL.
  4. Leakage check: for a label at time 01-02, the sale on 01-03 must not be sampled — RelBench's loaders enforce this.

Strictly speaking: RDL doesn't make feature engineering obsolete for every case — very small datasets, or domain knowledge that isn't in the database, still favour hand features. And "<1 hour" assumes a working RDL stack.

In code (RelBench + PyG)

from relbench.datasets import get_dataset
from relbench.tasks import get_task
from relbench.modeling.graph import make_pkey_fkey_graph
from torch_geometric.loader import NeighborLoader
ds   = get_dataset("rel-stack", download=True)
task = get_task("rel-stack", "user-engagement", download=True)
data, col_stats = make_pkey_fkey_graph(ds.get_db(), col_to_stype_dict, text_embedder_cfg)
loader = NeighborLoader(data, num_neighbors=[128, 128], time_attr="time",   # temporal sampling
                        input_nodes=("users", train_table.node_ids), input_time=train_table.times)
# model: PyTorch Frame encoders per table -> HeteroGraphSAGE -> MLP head

Proof workshop: A SQL aggregate is a message-passing layer

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. Tables: customers(id), transactions(id, customer_id, product_id, ts, amount), products(id, price). For a training row \((c,t)\), consider (a) COUNT(*) of \(c\)'s transactions in \((t-30,t]\), and (b) the average price of the products \(c\) bought in \((t-30,t]\). Write each as message passing on the relational entity graph, and find the minimum number of layers each needs. Then state the time rule every message must obey, and give a label that a model breaking it would fit perfectly.

Hint 1
(a) needs only edges customer \(\leftarrow\) transaction. Where does the price live?
Hint 2
Messages carry timestamps; a message from an event at time \(\tau\) may enter the prediction at \(t\) only if \(\tau\le t\).
Solution
(a) One layer: \(h_c=\sum_{e\in T(c)}\mathbf 1[t-30<\tau_e\le t]\), a sum aggregator with a time-masked constant message. (b) Two layers: first product \(\to\) transaction (each transaction copies its product's price, \(h_e=\mathrm{price}_{p(e)}\)), then transaction \(\to\) customer with a masked mean, \(h_c=\mathrm{mean}\{h_e:e\in T(c),\ t-30<\tau_e\le t\}\). One layer cannot do it: the customer's direct neighbours (transactions) do not carry price. Time rule: only messages with \(\tau\le t\). Breaking it: the label "will \(c\) make a transaction in \((t,t+7]\)" is computed exactly by a one-layer count over \((t,t+7]\), so a leaky model fits training data perfectly and is useless at prediction time. \(\square\)

Why it matters. Each layer is a learnable join plus an aggregate; depth is the length of the foreign-key path. This is the precise sense in which a relational GNN "automates feature engineering", and the time rule is what separates it from a leaky one. On social data the same rule applies to retweet cascades: a feature computed after the prediction time is not a feature.

Sharper lens: what the graph inherits from the schema

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.

precise statement

Why trees beat deep nets on one table: a measured answer

The slides' hypothesis is that the information is gone before deep learning starts. Grinsztajn, Oyallon and Varoquaux (NeurIPS 2022) measured three further reasons on 45 datasets, all about inductive bias. (1) Neural networks prefer smooth functions; tabular targets are irregular, with jumps. (2) Uninformative columns hurt MLPs much more than trees. (3) Tabular data is not rotation-invariant: each column means something, while an MLP learns equally well, or badly, on any rotation of the feature space, and such learners provably need more samples when few features matter (Ng 2004). Trees split on one column at a time, which is the right prior.

The picture changed in 2025: TabPFN v2 (Hollmann et al., Nature 2025), a transformer trained only on synthetic tables drawn from a prior over causal mechanisms, beats tuned gradient boosting on small tables (up to about 10,000 rows) in one forward pass. It is the single-table precedent for the relational foundation models of Lectures 13 and 14, and for the "prior-fitted" models in Lecture 14's Frontier section.

where it breaks

The entity graph depends on how the database was designed

The same facts can be stored in different schemas. Keep each product's brand as a text column, or normalise it into a brands table with a foreign key. A database designer sees a lossless transformation chosen for storage and consistency. The relational entity graph is not the same graph: in the first design two products of one brand are unconnected rows that merely share a feature value; in the second they are two hops apart through a brand node and exchange messages.

So RDL removes feature engineering from the columns and leaves one modelling decision in the schema: which shared values deserve to be nodes. Promote a categorical column to a table when rows that share its value should inform each other (brand, merchant, device, IP address in fraud); leave it a feature when the value only describes the row. The model is not invariant to this choice, and a benchmark result is always a result for one schema.

second viewpoint

The ancestor, and the one-way street between SQL and message passing

Deep Feature Synthesis (Kanter and Veeramachaneni 2015, the Featuretools library) already automated the data scientist of section 5: stack aggregation primitives along foreign-key paths, for example MEAN(orders.SUM(items.price)), generate thousands of such columns and give them to boosted trees. It beat most human teams in the competitions it entered. RDL is that idea with learned, differentiable primitives trained end to end, which is why "DFS + LightGBM" is the baseline every RDL paper must beat.

The slogan "a GNN layer is a JOIN plus GROUP BY" holds in one direction. Every sum or mean over primary–foreign-key edges is a layer. Not every query is: COUNT(DISTINCT …) across two hops, a ratio of two aggregates (the network must learn to divide), and above all non-equi joins ("orders placed within 7 days of another order by the same customer") are not foreign-key edges and do not exist in the entity graph unless you add them. Time encodings recover part of this. Knowing the gap tells you which hand-made features are still worth adding.

Lab: hands-on and practical tips

notebook · L12 relational deep learning builds a small e-commerce database, turns it into a graph, defines a training table, writes the SQL-feature + gradient-boosting baseline with DuckDB and trains a temporal relational GNN, with a leakage experiment.

The cutoff is the whole disciplineEvery example in the training table is (entity, time, label). The GNN may only aggregate rows with timestamp ≤ time; in the figure above the dashed orders are the leak. In PyG/RelBench this is NeighborLoader(time_attr=…); in SQL it is a WHERE ts <= cutoff you must never forget.
Beat the data scientist honestlyThe baseline is hand-written aggregates (SUM of purchases over 30/90 days, counts, recency) fed to XGBoost. A counterpoint paper in the atlas shows fixed aggregation features can rival GNNs; your RDL result is only interesting if that baseline was tuned.
Encode each column by typeNumbers: normalise; categories: embeddings; text: a sentence encoder; timestamps: cyclic features. RelBench's torch_frame does this per column; the row embedding is the node's input feature.
Your dataset is already an RDL problemUsers, tweets, retweets, follows and hashtags are tables with keys. rel-stack (Stack Exchange) is the closest public analogue; prototype there before touching your X data.

Readings & lookup guide

lecture notes CS224W course notes (Leni Aniva, Autumn 2024 — in your course folder)

Concise written version of the lectures; the walkthrough above cites it page by page.

read first Fey, Hu, Huang, Lenssen, Ranjan, Robinson, Ying, You, Leskovec — Relational Deep Learning: Graph Representation Learning on Relational Databases (ICML 2024 position paper)

arXiv:2312.04615 · ~2 h · the vision paper behind this lecture
  • Read: §2 (relational entity graph, training tables), §3 (temporal message passing, the GNN-as-SQL analogy), §5 (open research directions — a goldmine for projects).

benchmark Robinson, Ranjan, Hu, et al. — RelBench: A Benchmark for Deep Learning on Relational Databases (NeurIPS 2024 D&B)

  • Read: §3 (datasets & tasks, temporal splitting), §5 (the user study vs data scientists), Table of results. Use the website's leaderboards as a lookup.

roots Friedman, Getoor, Koller, Pfeffer — Learning Probabilistic Relational Models (IJCAI 1999)

Classic statistical relational learning; skim §1–2 (~40 min)
  • See how the same "database as a structured world" idea was approached with graphical models — useful for your neuro-symbolic perspective.

Homework 3 & deadlines

Homework 3 out Thu 10/29 · due Thu 11/12

Expected at web.stanford.edu/class/cs224w/homework/CS224W_Aut2627_HW3.pdf — not yet released when these guides were built (Oct 7). Save into the course folder.

Likely covers Lectures 9–13: heterogeneous GNNs (R-GCN parameter counts), KG embedding expressiveness proofs, recommender losses (BPR vs binary), and relational deep learning.

Colab 3 due 11/5 · Colab 4 out 11/5 · due 12/1 · Milestone due 11/10

An RDL project on RelBench (any of the 30 tasks) is an excellent, well-supported course project.

Self-check

In a relational entity graph, nodes are …

  1. tables
  2. rows of all tables
  3. columns
  4. SQL queries

\(\mathcal V=\bigcup_T T\); tables become node types.

The training table contains …

  1. all features
  2. the schema
  3. (entity ID, timestamp, label)
  4. only test labels

Labels are time-stamped; the same entity can have different labels at different times.

An inner join on pkey = fkey corresponds in the graph to …

  1. PK–FK edges
  2. node features
  3. the training table
  4. temporal encodings

\(a_{ij}=1\) iff \(r_i.\text{pkey}=s_j.\text{fkey}\).

How does RDL prevent time leakage?

  1. Random splits
  2. Dropping timestamps
  3. Using only static tables
  4. Temporal neighbour sampling: only rows with time ≤ label time

Built into the data loader.

The slides' hypothesis for why deep learning hasn't dominated tabular ML is …

  1. trees are always better
  2. single tables already contain engineered features, losing the relational information
  3. GPUs are too slow
  4. tables are too small

Flattening throws away what deep models could learn from.

Flashcards (click to flip)

RDL in one line
End-to-end deep learning on relational tables via a temporal heterogeneous GNN on the entity graph.
Schema graph vs entity graph
Tables & links vs rows & PK–FK edges.
Three things to define a task
Entity · label · time.
GNN layer ≈ SQL
JOIN (PK–FK edges) + learnable GROUP BY aggregation + temporal encoding.
RelBench
7 databases, 30 tasks, temporal splits, PyG + PyTorch Frame.
User study result
GNN ≥ expert (12 h, 682 LoC) with <1 h, 54 LoC.

History & the bigger picture

  • 1970 — Codd's relational model (IBM): data as relations, queried declaratively. SQL (1974) follows. Half a century later, most enterprise data still lives here.
  • 1999–2007 — Statistical Relational Learning: probabilistic relational models, Markov logic networks (Richardson & Domingos 2006), relational dependency networks.
  • 2010s — feature stores and AutoML (e.g. Deep Feature Synthesis, 2015) automate aggregation features but keep the flatten-then-learn paradigm.
  • 2023–2025 — RDL, RelBench, and relational foundation models (Lectures 13–14: RelGNN, Relational Graph Transformer, Relational Transformer, Kumo's commercialisation).
Economics · "data is the new oil"

The Economist's 2017 cover (on slide 6) framed data as the world's most valuable resource. RDL is an attempt to make the refinery cheaper: if months of data-science labour collapse into hours, the economics of who can build predictive systems change — favouring organisations with data over organisations with large data teams. It also concentrates power where data already accumulates, raising the governance questions about personal data that ride along with every churn model.

Classic SNA bridge

In this lectureClassic SNA counterpartWhat carried over, what changed
Relational entity graph: rows are nodes, keys are edgesRelational data in sociology: the "attribute × relation" data cube (Wasserman & Faust 1994, ch. 3); event-based network dataSNA always had actors, affiliations and attributes in separate tables and joined them by hand. RDL automates the join and learns the aggregation.
Training table (entity, time, label)Event-history / survival analysis of ties and actors (Snijders' SIENA models)Stochastic actor-oriented models also condition on the past to predict the next change. RDL's training table is the supervised-learning version of the same temporal discipline.
GNN layer = JOIN + GROUP BYEgo-network aggregation: alter attributes summarised per ego (mean friend income, share of same-party alters)Those hand-made ego-network features are exactly the SQL aggregates the lecture says the GNN learns. The GNN also learns which ones.
Time leakageReverse causation and "selection on the future" in observational network studiesBoth fields have a version of using information that did not exist yet. Shalizi–Thomas is the SNA warning; the cutoff is the RDL remedy.
RelBench tasks: churn, sales, readmissionTurnover and participation studies in organisational networks (Krackhardt & Porter 1986)Will this user leave in 90 days? is the classic turnover question with a network component. RelBench gives it an evaluator and a public leaderboard.
Bridge idea

Pose "will this account become inactive within 30 days?" as a RelBench-style task on your X tables (users, tweets, retweets, follows). Compare a temporal relational GNN against (a) hand-made ego-network aggregates plus boosting and (b) a SIENA-style actor-oriented model on a subsample. Three traditions, one question, one evaluator: a clean chapter.

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 9 · Beyond pairwise: higher-order, temporal, multilayer (relational deep learning: databases as temporal, typed graphs).

Connecting to your research

For SNA and your infrastructure
  • Your X/Twitter dataset is almost certainly stored as tables (users, tweets, retweets, follows, hashtags) — i.e. it already is an RDL problem. RelBench's rel-stack (Stack Exchange: users, posts, comments, votes, badges) is the closest public analogue — use it to prototype.
  • Tasks like "will this account become inactive / be suspended / start posting about topic X in the next 30 days?" fit the training-table formalism directly, with built-in leakage protection.
  • Neuro-symbolic hook: the GNN-as-SQL analogy invites the reverse direction — extract the learned aggregations back into readable SQL/logic rules for interpretability.

Frontier 2025–26: what changed since the slides

ICML 2026RDL is small but fast-growing, and concentrated at ICML — Relational foundation models, synthetic pre-training data (PluRel) and scaling laws are the new questions of the 12-paper cluster. The vendor claim KumoRFM-2 (April 2026) of ~5% over supervised RelGNN is not yet replicated.sources: arXiv:2604.12596 · arXiv:2502.06784 · arXiv:2505.10960
ICLR 2026Relational Transformer: 22M parameters, 93% of supervised AUROC zero-shot — Tokenise each cell with its table and column names and any schema maps into one input space (Lecture 14). The schema becomes part of the input, which is why the model transfers across databases.sources: arXiv:2510.06377
2006 → 2026The neuro-symbolic through-line — Markov logic networks (2006): the schema is a template for a graphical model. RDL (2024): the schema is a template for a computation graph. Relational transformers (2026): the schema is part of the input. Statistical relational learning never went away; it changed what the schema parameterises.sources: arXiv:2510.06377
AtlasStrong non-GNN baselines — One of the four threads of the cluster is "strong non-GNN baselines": fixed aggregation features plus boosting remain competitive on several RelBench tasks. The lecture's "GNN matched an expert in under an hour" result is real; so is the baseline's resilience. Update, October 2026: Revisiting Simple Baselines for Relational Deep Learning finds that fixed feature propagation + MLP + Correct & Smooth recovers a substantial part of heterogeneous-GNN performance on RelBench, and names the missing piece: a canonical way to build the target-to-target graph that label propagation needs. RT-J scales Relational Transformer pretraining. Read both before trusting any single leaderboard gap.sources: arXiv:2610.20534 · arXiv:2610.17867
Open question to carryMuch of the world's valuable data lives in SQL tables. Can one model generalise across schemas, and what is the relational-algebra equivalent of attention (Lecture 13 gives one answer)?
Frontiers · a database is a graph · only prior-fitted models beat a tuned GNN

Words & phrases

TermSimple meaningPersianIn context
impedance mismatchphrase(borrowed from electronics) when two systems' formats don't fit, so data must be awkwardly convertedناهمخوانی ساختاری"The impedance mismatch: ML wants one table"
ETLabbr.Extract, Transform, Load — the data-engineering work of moving and reshaping dataاستخراج، تبدیل، بارگذاری"months of ETL and feature work"
foreign keyn.a column that points to a row of another tableکلید خارجی"every foreign key becomes an edge"
primary keyn.the column that uniquely identifies each row of a tableکلید اصلی"rows are identified by their primary key"
timestampn.the recorded time of an eventمهر زمانی"only messages with an earlier timestamp"
joinn./v.combining rows of two tables that match on a keyالحاق (پیوند جدول‌ها)"a GNN layer is a learnable join"

Go deeper

  • Next: Lecture 13 — better architectures for RDL: composite message passing (RelGNN) and relational graph transformers.
  • Open problems (from the RDL paper): foundation models across databases, handling schema changes, explainability as SQL, scaling to billions of rows.
  • Question to hold: if a GNN layer is a learnable join, what is the relational-algebra equivalent of attention? (Lecture 13's transformers give one answer.)