Paper deep dive · relational prediction

RT-J: learn from the database,
not just a flattened table

A relational transformer can predict a missing or future value using a small set of examples—if its training and its retrieved context are designed for that job.

Paper: RT-J: Large-Scale Pretraining of Relational Transformers for Context-Efficient Predictions
Rishabh Ranjan and colleagues · Full paper · PDF · Models, data and code

Why predicting one cell can require several tables

Suppose you want to predict whether a user will click an advertisement. The query row identifies a user and a product, but the useful evidence may live elsewhere: the user’s segment, the product’s category and price, and previous clicks involving related users or products. A relational database stores these facts in separate tables connected by primary and foreign keys.

The conventional route

Join and aggregate the evidence into one feature row: purchase count, average price, recent activity, and so on. Then use a tabular predictor.

This can be very strong. But the features determine which details and relationships survive. Averages can hide which particular events involved which products.

The RT-J route

Retrieve a small, connected piece of the database. Keep its cells, table and column names, and key relationships. Predict the masked target cell directly.

The model learns from labeled task rows in that same context, without updating its weights for each new task.

In-context learning means adapting through the input, rather than through training steps. The frozen predictor sees historical examples with known outcomes alongside a query with its outcome hidden. It uses these examples to infer what prediction is being requested.

prediction = frozen_model(shared relational context, query target masked)

The word shared matters. If five examples refer to the same product, its cells need appear only once. Building an independent neighborhood for each example would repeat those cells and consume the input budget.

8,192maximum training context, measured in database cells—not text tokens or rows
~225labeled examples that fit on average at that budget in the main comparison
~10×fewer examples to match strong regression pipelines in the reported aggregate comparison

These are different quantities. How many labels fit depends on the schema and how many supporting cells are collected. The 10× result is example efficiency, not a claim of 10× lower latency or training cost. [Paper §§2, 5; Appendix J.1]

Retrieve globally, then explain locally

RT-J’s main contribution is a training-and-inference recipe around an existing relational transformer, not a wholly new backbone. The crucial retrieval idea separates two decisions: which labeled examples are worth seeing? and what surrounding evidence makes those examples useful?

Stage 1: use graph proximity to rank examples

Treat each database row as a node and each primary–foreign-key relationship as a traversable link. Start many random walks at the query row. At each step, choose uniformly among temporally valid neighboring rows. Count visits only to other rows in the target table. A historical click reached repeatedly through shared users and products becomes a promising support example.

The default uses 10,000 walks of 20 steps. These are finite random walks starting at the query; the procedure does not require a vector index or a learned similarity embedding. “No pre-computation” here refers to retrieval scores or vectors, not to dispensing with database loading and key adjacency access.

A subtle implementation detail: Appendix I makes the recency flag precise. With ρ = 0, candidates are ordered by visit count. With ρ = 1, timestamp is the primary sort key and visit count breaks timestamp ties. This is a switch between ranking rules, not a smooth weighted blend of relevance and freshness.

Stage 2: spend the remaining budget on local evidence

Use the ranked task rows as seeds for bounded-width breadth-first search (BFS). Each seed gets a local cell allowance, and all retrieved cells share one global allowance. A small local allowance spreads the budget across more examples; a large allowance spends more on explaining each example. The width bound limits how many neighbors BFS explores.

KnobMeaningTraining values
LTotal input cell budget512–8,192, powers of two
ℓLocal cell budget per seed128–8,192, powers of two
bBFS width bound8–256, powers of two
ρVisit-first or recency-first ranking0 or 1

Training randomly varies these settings. That exposes the model to different evidence layouts before anyone tries to tune the layout at test time. Context length varies by batch, with adaptive gradient accumulation to accommodate larger inputs. [Paper §4; Appendices G, I]

What does the transformer actually see?

A cell becomes an embedding that combines its value and the text meaning of its column and table names. For example, “price of product” carries a different prior than “age of user,” even if both values are numbers. The frozen text encoder is all-MiniLM-L12-v2. Keys specify connectivity rather than supplying arbitrary identifier-value embeddings.

Three attention routes

  1. Column: compare cells in the same table and column across rows.
  2. Feature: combine cells in the same row and its referenced parent rows.
  3. Neighbor: receive information from child rows that reference the current row.

The parent/child distinction is explicit in Appendix F. This is more specific than unrestricted attention over every cell.

One masked-cell interface

The architecture has 12 blocks, hidden size 512 and eight attention heads. Its exact trainable parameter count is 85,562,530, excluding the frozen text encoder—rounded to 86M in the paper.

During pretraining, type-specific heads regress normalized targets with Huber loss, including binary labels. This is not an autoregressive text-generation model. The released recipe masks only the target cell.

The Join: real schemas plus mechanically checked tasks

A model cannot learn these relationships from arbitrary spreadsheets alone. RT-J first trains on synthetic multi-table data from PluRel, then continues on a real-world corpus called the Join. The full corpus contains 639 databases, 6,023 generated forecasting tasks, and roughly 11,000 autocomplete tasks.

  1. Collect and preserve structure. Source-specific collectors ingest public dumps and APIs into Parquet tables with primary-key, foreign-key and time-column metadata. Sources overlapping the evaluation benchmarks are excluded by source identity.
  2. Repair representation, conservatively. Normalize booleans, numeric strings and timestamps; infer missing foreign keys using names and at least 80% value containment. Identifier-like fields such as zip codes and ISBNs are protected from numeric coercion. Large databases are subsampled by entity while retaining associated activity histories.
  3. Ask an LLM for constrained task proposals. The proposer chooses among 25 template families: counts, churn, trends, ranking, novelty, rare events and more. It receives schema summaries and examples, not permission to invent arbitrary unsupported columns.
  4. Check and filter deterministically. Scripts validate columns, foreign keys and templates. Historical baselines and a fixed XGBoost pipeline filter trivial, broken or strongly drifting tasks. Difficult non-trivial tasks can remain even when XGBoost finds little signal.

An autocomplete task masks a value already present in the database. A forecasting task requires a new label table: for example, one row per account and prediction date, with the maximum balance over the following window as its target. At prediction time that future-derived target is hidden.

Valid SQL is not the same as a meaningful task. The appendix’s manual audit found many domain-relevant targets but also about 100 tasks aggregating non-semantic columns. Deterministic checks improve correctness; they cannot establish business relevance on their own.

Not all collected data enters the released model’s pretraining run: memory limits restrict the real-data phase to 523 databases and 13,243 tasks. Each phase takes about a day or less on eight A100 GPUs. Relative to the earlier RT recipe, this work also uses approximately 11× more tokens, up to 8× larger contexts, a 4× larger model and roughly 70× more pretraining FLOPs. The improvement is a combined recipe-and-scale result, not a compute-matched isolation of one trick. [Paper §§3, 5; Appendices D, G, H]

Build a context, one budget decision at a time

This miniature database contains click-query rows linked to users and products. The query is at day 10. Historical labels are available; days 11 and 12 are future evidence. Run the two-stage sampler, change its budget, and inspect exactly what made it into the context.

Seed

Teal = selected support/evidence; blue = masked query; pale gray = not selected; dashed red = future row blocked by time gate. Lines are key links, not learned similarity.

cells used / total budget
support labels included
toy mean of selected labels

Candidate ranking

Collected rows

Try these three experiments.
  1. Use a small global budget. Raise the local allowance: do you get richer neighborhoods but fewer independent labels?
  2. Switch between visit-first and recency-first ordering. Recency can favor a newer, less-connected example.
  3. Disable the time gate. Future rows can now influence both walks and context. A plausible-looking estimate is not evidence that the experiment is valid.

What this prototype does—and does not—reproduce. It runs real seeded random walks over key links, ranks task rows, and collects a deduplicated context using local BFS. For clarity it reserves the query first, packs whole rows atomically, and uses tiny budgets and a simple shuffled neighbor cap. Production RT uses a cell collector and much larger contexts. Here each click row costs three cells (day, channel, label), each user one cell (segment), and each product two (category, price); key identifiers cost no value tokens.

The displayed number is an unweighted average of selected binary labels, not an RT-J prediction, calibrated click probability, or quality score. It ignores the collected features and exists only to show how evidence selection can change an answer. No model weights are included.

Compact prototype: the core algorithm
valid = time_safe_rows(database, query.time)
visits = Counter()
for walk in range(W):
    row = query
    for step in range(K):
        row = uniform_neighbor(row, valid)
        if row is None: break
        if row.table == query.table and row != query:
            visits[row] += 1

seeds = sort_support_rows(valid, visits, recency_flag)
context = unique_cells(query, mask_target=True)
for seed in seeds:
    context |= bounded_BFS(seed, local_cells, width,
                           valid, remaining_global_budget)
    if cells(context) == L: break

# Actual RT-J inference, not the toy mean above:
prediction = frozen_RT_J(context)

Strong few-example regression, more qualified classification

First, understand the comparison

The main evaluation uses RelBench: 21 forecasting tasks on seven held-out databases—nine regression and twelve binary classification tasks. Regression uses Z-score-normalized mean absolute error (nMAE; lower is better). In intuitive terms, the absolute error is measured relative to a task’s target scale. Classification uses AUROC (higher is better): how well positives rank above negatives across thresholds, not the accuracy of one threshold or the calibration of probabilities.

The four baselines combine either RDBLearn or an LLM-agent featurizer with either TabICLv2 or LightGBM. For each query, the baselines receive the same labeled task rows found in RT-J’s context. Their feature extraction is not restricted to the same supporting source cells. That is a label-matched comparison, not an equal input-token, latency or total-compute comparison. The main curves use the full test splits; several later ablations use an 8,192-row-per-task subsample.

Regression

RT-J leads every baseline at every tested example budget in the aggregate, by 2.3–5.0 nMAE percentage points. With about 15 examples it beats the best error the baselines reach with 225. The strongest extended baseline needs around 2,300 examples to surpass RT-J’s large-context result.

Classification

RT-J’s advantage is largest when labels are scarce: about 3.1 AUROC percentage points. The strongest pipeline catches up at the largest matched budget. With roughly 4,500 examples in the extended experiment, TabICLv2 pipelines exceed RT-J’s capped-context AUROC by 3.6–4.2 points.

“Leads in aggregate” does not mean “wins every task.” The per-task appendix reports cases where feature-based predictors lead, including item sales and driver position in regression. At large budgets classification is mixed. The results support a specific strength in the few-example regime—not universal dominance over tabularization. [Paper §5.1; Appendices J.1–J.2]

How much does real-data pretraining add?

The following are the paper’s Table 1 means. These include task-specific tuning and ensembling protocols, so they should not be mixed with the default single-context ablation numbers below.

ModelFine-tuned nMAE % ↓Fine-tuned AUROC % ↑In-context nMAE % ↓In-context AUROC % ↑
RT, random initialization29.2677.76——
RT-PluRel, synthetic pretraining27.5778.5332.9572.98
RT-J, synthetic → real27.1179.0232.3574.45

Real-data continuation improves the frozen in-context model by 0.60 nMAE points and 1.47 AUROC points over synthetic-only pretraining. Fine-tuning still produces substantially better mean metrics than the in-context pipeline, but it trains a predictor for each task. Frozen does not mean “no task-specific selection”: the in-context leaderboard pipeline scores 120 context configurations on up to 4,096 validation rows, then averages 16 predictions from four configurations and four context seeds. [Paper §5.2; Appendix A]

Retrieval quality is not simply label quantity

At 8,192 cells, feature-similarity retrieval and random walks effectively tie in aggregate quality. But the feature-similarity approach uses precomputed engineered features and fits many more labels. The chart shows mean label counts reported in §7.2; bars start at zero.

RDBLearn similarity
394
Random walks
223
Uniform support
208
Approximate mean labels in a fixed 8,192-cell context, from the retrieval ablation. Random walks: 33.4 nMAE / 72.9 AUROC; feature similarity: 33.5 / 73.0. Uniform support has nearly as many labels as random walks but is worse by about 4.1 nMAE and 6.1 AUROC points.

The lesson is not that walks always beat vectors. They are competitive here without the per-task feature pipeline. Similarity using RT-J’s own embeddings performs substantially worse than similarity using RDBLearn features. A vector index is only as useful as the representation it ranks.

What the remaining ablations teach

Sources: paper §7 and Appendices H, J.4. Schema and retrieval ablations swap components of the already-trained model at inference; they are not fresh, compute-matched training runs for each alternative.

Better context costs work—and validation labels

Context tuning

Choose (L, ℓ, b, ρ) on a validation split, then apply it on test. In the single-seed subsampled comparison, mean regression nMAE improves from 33.36 to 32.52. Classification worsens from 72.86 to 72.39 AUROC.

Some tasks prefer a smaller context. Item-sales chooses just 512 cells and improves from 14.00 to 11.79 nMAE. “Always use the largest window” is not supported.

Context ensembling

Sample multiple plausible contexts and average predictions. At the default configuration, going from one to sixteen contexts improves mean classification by about 1.1 AUROC points and regression by about 0.2 nMAE points.

It needs no extra labels beyond the support data, but requires sixteen sampled contexts and model passes. Individual tasks can get worse.

Tuning is not free adaptation: the reported search consumes up to 4,096 validation labels and, using shared prefixes, 144 validation passes plus a test pass. Ensembling can be parallelized, but parallelism reduces elapsed time only when hardware capacity is available; it does not eliminate total work.

Measured batch-1 settingCPU samplerGPU forwardTotal per example
10,000 walks × 20 steps28.06 ms10.03 ms38.09 ms
1,000 walks × 20 steps14.31 ms9.81 ms24.11 ms

Appendix I.1, Table 9: means across 21 tasks at L = 8,192 on one B200 GPU and an AMD EPYC 9565 CPU. These are hardware-specific inference timings, not end-to-end production SLAs. Reducing walks lowers latency but classification drops from roughly 72.9 to 72.1 mean AUROC for these two settings; regression changes little on average. Training-time CPU/GPU overlap does not make batch-1 retrieval latency disappear.

What remains unproven

Bottom line: RT-J is convincing evidence that a frozen relational model can use scarce labels well when its training distribution, schema semantics and evidence sampler fit the intended inference regime. The strongest result is context-efficient regression on the tested tasks—not universal superiority, causal reasoning, or free task adaptation.

One closing connection: For a context platform, this work suggests preserving typed schema names, key connectivity and point-in-time data access so that downstream predictors can assemble task-specific, budgeted contexts without flattening away all relational structure.

Source and reading map

This explainer is based on the full paper and its appendices. The toy database, browser simulation and interpretive cautions are teaching additions, not experiments reported by the authors.