NBFNet — what it is, what we run, and how to size it for PrimeKG

Reading order: [paper PDF](NBF Networks Paper.pdf) → this doc → PDR2 fork README. Source: Zhu, Zhang, Xhonneux, Tang. Neural Bellman-Ford Networks: A General Graph Neural Network Framework for Link Prediction. NeurIPS 2021. arXiv:2106.06935. Code: DeepGraphLearning/NBFNet.

1. The one-paragraph version

NBFNet learns a pair representation h_q(u, v) for every candidate (head, query, tail) triple by parameterizing the generalized Bellman-Ford algorithm. The idea: any path-based link prediction method (Katz index, personalized PageRank, graph distance, widest path, most reliable path) can be written as h_q(u,v) = ⊕_{P ∈ P_uv} ⊗_{e ∈ P} w_q(e) for some semiring ⟨⊕, ⊗⟩. NBFNet replaces these handcrafted operators with three learned neural functions: INDICATOR (boundary condition — sets h_u^(0) = q), MESSAGE (the ⊗ — DistMult / TransE / RotatE), AGGREGATE (the ⊕ — sum / mean / max / PNA). T layers of Bellman-Ford iteration give a representation of v conditioned on u and q; an MLP on that vector produces the link score. The crucial structural difference vs. RGCN/CompGCN is that NBFNet computes a separate, source-conditioned node representation for each query — every other GNN computes one shared embedding per node and decodes pairs from it.

2. Architecture in numbers (paper-default, FB15k-237 / WN18RR)

ComponentValueNotes
Layers T6T=4 already gets 0.409 MRR vs 0.415 at T=6 (Table 6b) — diminishing returns past 6
Hidden dim d32All hidden layers same dim
MLP head2 layers × 64 hiddenFinal score f(h_q(u,v)) → ℝ
Message functionDistMult (best)Hadamard product h ⊙ r. Also tried TransE (h + r) and RotatE (complex rotation). DistMult+PNA is best on FB15k-237 (Table 15).
Aggregate functionPNA (best)Principal Neighborhood Aggregation: concatenates {mean, max, min, std} × {1, log(deg), 1/log(deg)} = 12 channels, projected to d. Output dim is 13d before linear (12 + boundary self-loop).
OptimizerAdam, lr 5e-3Self-adversarial neg sampling, temperature 0.5 (FB15k-237) / 1.0 (WN18RR)
Batch256 / 128 positive32 negatives per positive
Epochs20
AugmentationReverse triples (v, q⁻¹, u)Doubles `
Edge dropoutYes — drop direct query edgesForces the model to learn non-trivial paths
Layer normYesAfter AGGREGATE
Residualshort_cut: yesPer layer if shapes match

Wall-clock on 4× V100: training 9.7 hr (FB15k-237), 4.4 hr (WN18RR); inference 4 min / 2.4 min.

3. Parameter count — the punchline

Table 8 in the paper:

ComponentFormulaFB15k-237 (|R|=474, T=6, d=32, MLP m=64)
INDICATOR|R| × d15,168
MESSAGET × |R| × d × (d+1)3,003,264
AGGREGATET × d × (13d+3)80,448 (PNA)
MLP f(·)m(2d+1) + m + 14,225
Total3,103,105

Three properties to internalize:

  1. No |V| term. NBFNet has no entity embedding table at all. Initial node states are zero except for the query source, which gets the query embedding. Every other node’s representation is derived by message passing.
  2. No |E| term. Edge representations are reused per relation type, not per edge. (w_q(x, r, v) = W_r q + b_r.)
  3. Linear in |R|. The MESSAGE block dominates and grows like T × |R| × d². So scaling pain is in the relations, not the graph.

This is why TransE needs 30M params on FB15k-237 (one d-dim vector per node) but NBFNet needs 3M (none).

4. Time and memory complexity

Per Bellman-Ford run:

  • Time: O(T · (|E|d + |V|d²))
  • Memory (naive): O(|E|d) — every edge holds a message vector
  • Memory (fused rspmm): O(|V|d) — custom CUDA kernel computes message + scatter-add in one pass without materializing messages

Amortized per triple (one BF run scores |V| candidates simultaneously): O(|E|d/|V| + d²). Compared to RGCN’s O(|E|d²) and GraIL’s O(|E|d²), NBFNet is the only inductive method that’s not quadratic in d along the dominant |E| term.

5. ULTRA — what our fork actually is

Our lib/pdr2/code/ultra/ is not plain NBFNet. It’s ULTRA (Galkin et al. 2024), a strict superset that addresses NBFNet’s one remaining transfer limitation: per-relation parameters. ULTRA stacks two NBFNets:

                ┌─────────────────────┐
query relation ──►│   RelNBFNet (6L)    │── query-conditioned
                │ on graph of relations│   relation embeddings
                │  (4 fundamental rels:│   (one per |R|, per query)
                │  h2h, h2t, t2h, t2t) │
                └──────────┬──────────┘
                           │
                ┌──────────▼──────────┐
(h, ?, ?, KG) ─►│  EntityNBFNet (6L)  │── pair scores h_q(h, v)
                │   on the actual KG   │   for all v ∈ V
                └─────────────────────┘

The relation graph is universal: 4 fundamental interactions (head-to-head, head-to-tail, tail-to-head, tail-to-tail) regardless of how many real relations the KG has. So the only thing that changes when you swap in a new KG is the data — no new parameters. Pretrained ultra_3g.pth, ultra_4g.pth, ultra_50g.pth are ~2 MB each (≈168K parameters total) and transfer zero-shot to any KG. Local copies of these checkpoints live in ~/git/ULTRA/ckpts/ once the notebook downloads them.

Our lib/pdr2/code/ultra/models.py defines:

  • Ultra — the wrapper that runs both NBFNets in sequence
  • RelNBFNet — boundary uses torch.ones(d) instead of a query embedding (it operates on the relation graph; the query is a node there)
  • EntityNBFNet — boundary uses the relation embeddings produced by RelNBFNet, fed in via self.query and layer.relation before forward

Both inherit the canonical NBFNet ops (remove_easy_edges, negative_sample_to_tail, beam-search visualization) from base_nbfnet.py:BaseNBFNet, but each overrides bellmanford and forward: the loops Ultra runs are RelNBFNet.bellmanford and EntityNBFNet.bellmanford in models.py, and BaseNBFNet.bellmanford never runs. (Corrected 2026-10-30, #1131: this pointed at the base class’s loop.) The actual message-passing convolution is layers.py:GeneralizedRelationalConv and keeps upstream NBFNet’s DistMult/TransE/RotatE message functions and PNA. Its fused rspmm kernel differs from upstream in one place. The kernel vendored from the PDR2 release set nnz = edge_index.size(0), which is always 2, so a graph’s highest-numbered node aggregated no messages; upstream ULTRA fixed this in c414f83 (2024-03-30). PR #918 (merged 2026-10-12; #854, D-Q4-25) runs upstream’s fix (FIXED) for new training and scores the checkpoints trained before it (smoke run 1, Run 2’s Arms A and B) in LEGACY mode, recorded per checkpoint. See ultra/rspmm_semantics.py.

6. Our config, side-by-side with the paper

Every Vertex foundation reads lib/pdr2/code/config/maple_container.yaml, with launch-time overrides (REMOVE_ONE_HOP, VAL_CURVE_*, KNOWN_NEGATIVES); it follows transductive/inference.yaml, which no Vertex run reads, plus a few keys. The PrimeKG Colab config is inlined in lib/pdr2/notebooks/pdr2_run_primekg.ipynb. Where the trainer ignores the YAML, resolved_config.FOUNDATION_AS_RUN records what ran (#861). (Corrected 2026-10-30, #1131: this named only inference.yaml and the notebook.)

KnobPaper (FB15k-237)Our PDR2 (PrimeKG)Why we differ
T (layers)66Same
d (hidden)3264ULTRA default — relation graph reps benefit from extra capacity
Message funcDistMultDistMultSame
Aggregate funcPNAsumULTRA default — PNA’s [1, log_deg, 1/log_deg] scaling can blow up on PrimeKG super-hubs (avg deg 125, max deg ~10⁴ on protein-protein nodes); sum is safer until we measure
OptimizerAdamAdamW in the configs, but the Vertex trainer never reads the YAML block (#861). It builds Adam (weight decay 1e-4) unless the payload’s optimizer knob asks for AdamW: D-Q4-41 call 6A, 1944e53 (#1078), knobs in training_knobs.py. (2026-10-24, #1226: this row used to say Adam was hard-coded.)Weight-decay is helpful for the larger ULTRA
LR5e-35e-4 in the configs. The Vertex trainer’s default is a flat 1e-4: its plateau scheduler is never stepped (#861). The payload’s learning_rate knob sets it (1944e53); the proving ground’s cell 2, its control arm (D-Q4-43, #1110), trained at Adam 5e-4Not measured: 5e-4 is upstream ULTRA’s rate, and the trainer’s 1e-4 came with the PDR2 release (#861). Maple’s one comparison, proving-ground cells 1 and 2, favoured 5e-4 over 1e-4 on S3 (D-Q4-43, #1110); no run has tried 5e-3. (Corrected 2026-10-30, #1131: this cell said 10× lower was empirically necessary past ~1M edges.)
Negative weightingSelf-adversarial, temperature 0.5 / 1.0None on Vertex: plain mean BCE over the positive and its 10 strict negatives. adversarial_temperature is read only by pretrain.py and run_kgia.py (#861)Inherited from the PDR2 release
Batch256 pos × 32 neg = 8,192512 × (1 + 10) configured, halved on out-of-memory unless pinned (pinned_batch_size, 1944e53). Every unpinned full-split run on the A100 80GB trained at 64: smoke, Run 2 (#523), Run 3. Its resolved_config.json still says 512; the log’s batch_size= lines give the real one. 64 (3g/4g pretraining). (Corrected 2026-10-30, #1131: this row gave only 512.)Memory-bound by node states × layers × batch (fused rspmm)
Epochs2020 on Vertex: the smoke foundation (f1228371) and both Run 2 arms. Arm A was extended to 40 under gate S2’s rule (#523). Run 3 keeps 20, extended to 40 only under S2’s rule (D-Q4-37 Call 3, #1008). The PrimeKG Colab notebook set 5 (10 for GP-KG joint pretrain)The Colab 5 was a compute budget (1 Colab Pro+ session ≈ 6 hr); Vertex jobs have no session limit
BPE(full epoch)500 batches/epochSubsampled — full epoch on PrimeKG would be ~16K batches
Edge dropoutDrop query edgesremove_one_hop: yes on every run of record since Run 2 Arm A, set at launch with REMOVE_ONE_HOP=yes. maple_container.yaml still says no, and False is the base_nbfnet.py default every earlier foundation trained withThe default drops only the query edge and its inverse (t→h, r⁻¹) and leaves the mirror (t→h, r) in the graph, a shortcut gate S0 confirmed (filtered MRR 1.00 with the mirror vs 0.03 without, #523). yes drops every edge, of any relation and in either direction, between each query’s head and tail
Reverse augYesYesSame — required by the bellmanford loop’s symmetry

7. Resizing for PrimeKG — concrete options

PrimeKG numbers (per docs/KG_CATALOG.md):

  • |V| = 129,375 entities
  • |E| = 8,100,498 edges (already bidirectional)
  • |R| = 30 relation types (60 with reverse)
  • avg degree ≈ 125 (≈6× FB15k-237’s avg deg 21, ≈2× Hetionet’s 96)

What is not a problem

  • Parameter count. With |R|=60 and ULTRA’s relation-graph trick, our model is ~168K parameters total — smaller than NBFNet on FB15k-237 (3M). PrimeKG won’t grow the model.
  • Inductivity. ULTRA + NBFNet are entity-agnostic. Adding/removing PrimeKG nodes between train and eval is fine.

What is a problem

  • Per-batch wall-clock. Bellman-Ford is O(T × |E| × d) per query. PrimeKG has 6.5× the edges of GP-KG → expect ~6× slower per batch. Notebook predicts ~9 sec/batch (we measured 3.3s on GP-KG).
  • Memory (without rspmm). Naive memory is O(|E|·d·batch_size). At d=64, batch=512: 8.1M × 64 × 512 × 4B = 1 TB. Fused rspmm drops this to O(|V|·d·batch_size) = 17 GB, but that is one layer’s node states, and training keeps every layer’s activations for backward. On an A100 80GB, ~103K-entity graphs ran out of memory at 512, 256 and 128 and fit 64 (#523, #1078); at PrimeKG scale, plan for ≤ 64 and pin it. (Corrected 2026-10-30, #1131: this said 17 GB was tractable on one A100/H100.)
  • Validation cost. PrimeKG’s standard split is ~1.6M valid triples. Per-triple eval at batch 512 needs ~3,200 batches → ~8 hr. The notebook subsamples val_n_sample=5000 for fast iteration; full eval is run once at the end overnight (~7-8 hr).

Knobs worth tuning, ranked by leverage

  1. Drop T from 6 → 4. Paper Table 6b: T=4 → 0.409 MRR, T=6 → 0.415 (1.5% delta) on FB15k-237. Per-batch time scales linearly with T. 33% wall-clock savings for ~1.5% metric loss is the best Pareto move if we’re compute-bound. (Try first.)

  2. Aggregate: sum → PNA. Paper Table 6a: PNA gives +7% MRR on FB15k-237 vs sum (DistMult+PNA 0.415 vs DistMult+sum 0.388). Adds ~6.5× the linear-projection params per layer (output is 13d not 2d) but is essentially free at runtime — the rspmm kernel computes all four PNA stats in one pass. Try this on PrimeKG with the scale.clamp(min=1e-2) numerical guard already in our layers.py:171. PrimeKG’s high max-degree might still trip it; if loss goes NaN, fall back to sum.

  3. Hidden dim 64 → 96 or 128. ULTRA’s d=64 is a guess inherited from upstream — the original NBFNet found d=32 was enough for FB15k-237. PrimeKG has more entity types (10 vs 1) and more semantic structure, so capacity should help. Cost: AGGREGATE linear is O(d²), MESSAGE is O(d) per edge, so doubling d quadruples the AGGREGATE cost but only doubles the dominant |E|d term. Test d=96 first; only go to 128 if metrics warrant.

  4. Learning rate schedule. The trainer’s default is a flat Adam lr=1e-4, not the configs’ AdamW 5e-4 (#861), and every foundation trained before 1944e53 ran at it. Since that build (D-Q4-41 call 6A, #1078) the payload sets the rate and the optimizer class (learning_rate, optimizer); the proving ground’s cell 2, now its control arm (D-Q4-43, #1110), trained at Adam 5e-4. The paper used a flat Adam lr=5e-3, 50× the default, on a 10× smaller graph. A schedule is not a knob: cosine decay or warmup is cheap to add, but it is a code change. Run 3 does not change it: D-Q4-37 Call 3 (#1008, decided 2026-10-17) keeps Run 2’s flat Adam 1e-4, so Run 3 stays comparable with Run 2. #861 closed with PR #890, which corrected the run records and changed no training. (Corrected 2026-10-24, #1226: this item said every Vertex foundation so far had trained at 1e-4.)

  5. Bidirectional BFS subsampling (paper Appendix G). For WikiKG90M (87M nodes), the authors restricted each query to a 2-hop bidirectional BFS subgraph with degree clamp m=100. This gives a guarantee: any path of length ≤ 2k between head and any tail candidate is preserved. PrimeKG is small enough that we don’t need this (our 8M edges fit fine), but this is the playbook if we ever pre-train on a PrimeKG + DRKG + Hetionet union (which would push past 50M edges). The k=2, m=100 settings are a sane starting point.

Knobs not worth tuning

  • Layers within RelNBFNet vs EntityNBFNet asymmetrically. Our config sets both to 6 — keep them in sync. RelNBFNet’s graph is tiny (4 fundamental relations × |R| nodes), so its T contributes negligibly to wall time.
  • Negative count. 32 negatives is paper-validated on three datasets. Going lower trades MRR for speed; going higher hits memory.
  • Removing layer norm or short-cut. Paper showed layer norm was needed for stability on FB15k-237. Don’t strip it unless we have a specific reason.

8. Open questions — things this audit can not answer

These need empirical runs, not paper-reading:

  • Does PNA work on PrimeKG without numerical NaNs? Theoretically yes (the clamp protects it); practically need to A/B against sum on a 1-epoch run.
  • Does a sampled MRR track full-split MRR? Vertex runs no in-loop validation (val_n_sample: 0); eval_maple.py ranks post-hoc, on the full test split by default and a seeded 50K sample in Runs 2 and 3, whose 5,000-triple validation curve (#593) watches training. 5000 is the Colab notebook’s value. The calibration check is #122. (Corrected 2026-10-30, #1131: this said val_n_sample is currently 5000.)
  • Does increasing d from 64 to 96 actually help on PrimeKG, or does it just cost compute? No literature signal — needs an A/B.
  • Are high-degree hubs hurting message passing? Partly measured. Over the ~7,800 drug candidates for (?, treats, MONDO:0005575), Spearman(score, degree) was +0.839 for Run 2 Arm A (#523) and +0.70 to +0.86 for Run 3’s arms (run3_readout.md §6), all failing gate S5’s ≤ 0.6. Scores also track treats-subject count (about +0.5), so this shows popularity bias, not hub damage inside message passing. Whether degree-aware sampling removes it is open. (Corrected 2026-10-30, #1131: this listed the question as unmeasured.)
  • Is sum-aggregate creating loss-of-information that propagates through 6 layers? The paper only ran sum vs PNA on FB15k-237 (avg deg 21). PrimeKG (avg deg 125) is well outside that calibration regime.

9. Citations to keep in scope

For our own PDR/MODS docs, when referring to NBFNet:

Zhu, Z., Zhang, Z., Xhonneux, L.-P., & Tang, J. (2021). Neural Bellman-Ford Networks: A General Graph Neural Network Framework for Link Prediction. Advances in Neural Information Processing Systems 34 (NeurIPS 2021). arXiv:2106.06935.

For ULTRA (which is what we actually run):

Galkin, M., Yuan, X., Mostafa, H., Tang, J., & Zhu, Z. (2024). Towards Foundation Models for Knowledge Graph Reasoning. International Conference on Learning Representations (ICLR 2024). github.com/DeepGraphLearning/ULTRA.