57  Predicting from graph context, with honest coverage

Verbs: train_context_predictor + predict_with_context_predictor + conformalize_interval + conformalize · Background: context-conditioned posterior (Garnelo et al. 2018 CNP; Kim et al. 2019 ANP) + conformal coverage and its break under graph dependence (Vovk; Angelopoulos & Bates 2021; Barber et al. 2023; Tibshirani et al. 2019; CF-GNN, Huang et al. 2023; NAPS, Clarkson et al. 2023) · Checked: provenance (which rows informed each prediction) + measurement (coverage).

This is the tier Neptune structurally lacks: a graph-conditioned prediction with an honest coverage guarantee. It carries two results:

  1. A regression-conformal workflow that runs end to end. A Gaussian context predictor of a paper’s year — a high-offset target (2014–2020) that collapses (std ≈ 0.001, mean ≈ 2163) unless the engine standardizes it. Writing this recipe found that collapse; the engine now standardizes the predictor’s target and its context members’ values in z-space and de-standardizes what it serves. The recipe runs because of that fix.
  2. The conformal-under-shift lesson. The dataset’s time split breaks one crux and spares the other. The year interval under-covers, and the textbook weighted-conformal remedy moves it only a little; the subject-classification set holds its coverage, because the shift barely touches its score. Each outcome comes with the diagnostic that explains it.

Both are findings at full scale (4,000 papers, gte-modernbert-base). At small scale every cell below runs the same computation on the 400-paper core with a random-weight encoder: the numbers show the pipeline at work, and the findings are claimed at full only.

import tempfile

import jammi
import numpy as np
from jammi_cookbook import datasets, keystone, scale, shift
from jammi_cookbook.claims import claim

SCALE = scale.current()
ALPHA = 0.10  # ask for 90% coverage

db = jammi.connect(f"file://{tempfile.mkdtemp()}")
arxiv = datasets.arxiv(db, SCALE)
embeddings = keystone.embed(db, arxiv, SCALE)
propagated = keystone.propagate(db, arxiv, embeddings)

year = {
    r["paper_id"]: r["year"]
    for r in db.sql(f"SELECT paper_id, year FROM {arxiv.papers}.public.{arxiv.papers}").to_pylist()
}
cal_ids, test_ids = arxiv.split["valid"], arxiv.split["test"]
print(f"calibration era (2018): {len(cal_ids)} papers   test era (2019–): {len(test_ids)} papers")
2026-10-03T07:42:48.145020Z  WARN jammi_kernels::admission: fused-kernel domain check failed; falling back to the eager composition op="attention_block_fused" predicate="head_dim_is_attention_block_fixed_head_dim"
calibration era (2018): 122 papers   test era (2019–): 96 papers

57.1 Part A — year regression, conformalized

The predictor learns, across subjects, to read a paper’s year off the years of its nearest papers — a Neural Process: one task per subject, the context retrieved by embedding similarity at prediction time. It trains over the propagated (citation-conditioned) embeddings and records that table: every later prediction reads its context from the same vectors, whatever tables the source gains afterwards.

def train_year_predictor(db, arxiv: Arxiv, scale: Scale, embeddings: str) -> str:
    """Tier 04: meta-train a Gaussian context predictor of a paper's ``year``,
    one task per ``subject``, reading each target's context from its nearest
    papers in ``embeddings`` — the table the predictor then always serves
    from. Returns the predictor's model id."""
    job = db.train_context_predictor(
        arxiv.papers,
        embedding_table=embeddings,
        key_column="paper_id",
        task_column="subject",
        value_column="year",
        architecture="attncnp",
        output="gaussian",
        objective="crps",
        seed=0,
        **PREDICTOR_BUDGET[scale],
    )
    job.wait()
    return job.output_model_id

Each prediction is one predict_with_context_predictor call:

def predict_years(
    db, arxiv: Arxiv, predictor: str, keys: list[str]
) -> tuple[np.ndarray, np.ndarray]:
    """Tier 04: the predictor's served year distribution — mean and standard
    deviation — for each paper in ``keys``."""
    served = [
        db.predict_with_context_predictor(predictor, source=arxiv.papers, target_key=k)
        for k in keys
    ]
    return np.array([s["mean"] for s in served]), np.array([s["std"] for s in served])
predictor = keystone.train_year_predictor(db, arxiv, SCALE, propagated)
cal_mean, cal_std = keystone.predict_years(db, arxiv, predictor, cal_ids)
test_mean, test_std = keystone.predict_years(db, arxiv, predictor, test_ids)
cal_year = np.array([year[k] for k in cal_ids], dtype=float)
test_year = np.array([year[k] for k in test_ids], dtype=float)
pred_std = float(np.concatenate([cal_std, test_std]).mean())
print(f"predictor cal-era mean:  {cal_mean.mean():.2f}")
print(f"predictor test-era mean: {test_mean.mean():.2f}")
print(f"mean predictive std:     {pred_std:.3f}")
predictor cal-era mean:  2017.46
predictor test-era mean: 2018.09
mean predictive std:     0.997
claim("the Gaussian head does not collapse: its predictions keep their spread",
      pred_std > 0.05, f"standard deviation {pred_std:.3f} in z-space")
✓ the Gaussian head does not collapse: its predictions keep their spread (standard deviation 0.997 in z-space)

The interval comes from the engine: calibrate the absolute residual \(|y - \hat y|\) on the calibration era, apply its \(1-\alpha\) quantile to the test era.

intervals = db.conformalize_interval(
    cal_mean.tolist(), cal_year.tolist(), test_mean.tolist(), alpha=ALPHA
)
reg_cov = float(np.mean([lo <= y <= hi for y, (lo, hi) in zip(test_year, intervals)]))
reg_width = float(np.mean([hi - lo for lo, hi in intervals]))
print(f"nominal coverage:    {1 - ALPHA:.2f}")
print(f"interval coverage:   {reg_cov:.3f}")
print(f"mean interval width: {reg_width:.2f} years")
nominal coverage:    0.90
interval coverage:   0.938
mean interval width: 3.88 years
if SCALE is scale.Scale.FULL:
    claim("the time split breaks exchangeability, and the interval under-covers",
          reg_cov < 1 - ALPHA, f"coverage {reg_cov:.3f} against a nominal {1 - ALPHA:.2f}")

At full scale the interval under-covers: realised coverage falls below the nominal 0.90 — the later papers are not exchangeable with the earlier ones.

57.1.1 Weighting the interval does not restore coverage

The textbook covariate-shift fix is importance-weighted conformal: reweight the calibration residuals toward the test era before taking the quantile. It can only help if the calibration papers most like the test era carry the larger residuals the test era has. Whether they do is a property of the data, and the correlation below measures it. At full scale they do: residual size tracks test-era likeness, so reweighting toward the test era widens the interval and coverage rises. But the test era’s residuals run about one and a half times the calibration set’s — a spread shift no reweighting of the calibration residuals can reach, since the weights only redistribute mass over residuals the calibration set already has — so the weighted interval still falls far short of 0.90. On the small core the calibration papers most like the test era carry smaller residuals, so reweighting toward them narrows the interval and loses coverage.

A calibration paper’s test-era likeness is read off its neighbourhood: the share of test-era papers among its nearest calibration- and test-era papers, one query-by-example search each. Its odds estimate the paper’s test-to-calibration likelihood ratio, the weight weighted conformal needs.

def test_era_shares(
    db, arxiv: Arxiv, embeddings: str, keys: list[str], sizes: tuple[int, ...]
) -> dict[int, np.ndarray]:
    """Each paper's share of test-era (2019–) papers among its nearest
    calibration- and test-era neighbours, at each neighbourhood size — how
    test-era-like its neighbourhood is."""
    hoods = [
        neighbours(db, arxiv, embeddings, key, f"year >= {datasets.VALID_YEAR}", max(sizes))
        for key in keys
    ]
    return {
        size: np.array([np.mean([n["year"] > datasets.VALID_YEAR for n in h[:size]])
                        for h in hoods])
        for size in sizes
    }
SIZES = (10, 25, 50)
shares = keystone.test_era_shares(db, arxiv, propagated, cal_ids, sizes=SIZES)
test_shares = keystone.test_era_shares(db, arxiv, propagated, test_ids, sizes=SIZES)
likeness = shares[keystone.NEIGHBOURS]
# Weighted conformal weighs the calibration rows and each test row alike.
schemes = {
    size: shift.Weights(
        cal=shift.density_ratio(shares[size], size),
        test=shift.density_ratio(test_shares[size], size),
    )
    for size in SIZES
}

cal_resid = np.abs(cal_mean - cal_year)
test_resid = np.abs(test_mean - test_year)
wt_reg_cov = shift.score_coverage(
    cal_resid, test_resid, weights=schemes[keystone.NEIGHBOURS], alpha=ALPHA
)
reg_corr = float(np.corrcoef(cal_resid, likeness)[0, 1])
print(f"cal  mean |y−ŷ|: {cal_resid.mean():.3f}")
print(f"test mean |y−ŷ|: {test_resid.mean():.3f}")
print(f"weighted interval coverage:      {wt_reg_cov:.3f}   (Δ {wt_reg_cov - reg_cov:+.4f})")
print(f"corr(|residual|, test-likeness): {reg_corr:+.3f}")
cal  mean |y−ŷ|: 0.723
test mean |y−ŷ|: 1.045
weighted interval coverage:      0.719   (Δ -0.2188)
corr(|residual|, test-likeness): -0.796
if SCALE is scale.Scale.FULL:
    claim("residual size tracks test-era likeness, so the reweighting helps",
          reg_corr > 0 and reg_cov < wt_reg_cov,
          f"correlation {reg_corr:+.3f}; coverage {reg_cov:.3f} → {wt_reg_cov:.3f}")
    claim("and the test era's larger residuals keep it short of nominal",
          wt_reg_cov < 1 - ALPHA and test_resid.mean() > 1.25 * cal_resid.mean(),
          f"mean residual {test_resid.mean():.3f} against {cal_resid.mean():.3f}")

57.1.2 The provenance rail

A prediction carries its audit trail: source says how its context was assembled (ann, edges, hybrid) and context_ref names the rows that informed it. Asked to condition on the citation neighbourhood instead of embedding similarity, the same predictor reads its context off the graph:

target = test_ids[0]
by_similarity = db.predict_with_context_predictor(
    predictor, source=arxiv.papers, target_key=target
)
by_citation = db.predict_with_context_predictor(
    predictor, source=arxiv.papers, target_key=target,
    edge_source=arxiv.cites, edge_src_column="src", edge_dst_column="dst",
    edge_direction="out", edge_hops=2,
)
for how, served in (("similarity", by_similarity), ("citations", by_citation)):
    print(f"{how:<10} source={served['source']:<6} context={len(served['context_ref'])} papers "
          f"→ {served['mean']:.1f} ± {served['std']:.2f}")
similarity source=ann    context=32 papers → 2018.6 ± 0.86
citations  source=edges  context=15 papers → 2015.8 ± 0.87
claim("each context reports how it was assembled",
      by_similarity["source"] == "ann" and by_citation["source"] == "edges")
claim("and the citation context holds only papers the walk reached",
      all(ref in year for ref in by_citation["context_ref"]))
✓ each context reports how it was assembled
✓ and the citation context holds only papers the walk reached

57.2 Part B — subject classification under the same shift

The same lesson on a second task, with a complementary mechanism. The task is subject classification; the predictor is a nearest-neighbour vote over the propagated (citation-graph-conditioned, tier 02) embeddings: a paper’s class scores are the similarity-weighted subjects of its nearest training-era papers, found by a query-by-example search filtered to the training era. It is calibrated on 2018 and tested on 2019 onward.

def subject_scores(db, arxiv: Arxiv, embeddings: str) -> SubjectScores:
    """Tier 04: a paper's class scores are a vote of its nearest training-era
    papers in ``embeddings``, each weighted by its similarity."""
    subject = {
        r["paper_id"]: r["subject"]
        for r in db.sql(
            f"SELECT paper_id, subject FROM {arxiv.papers}.public.{arxiv.papers}"
        ).to_pylist()
    }
    classes = sorted(set(subject.values()))

    def scores(key: str) -> np.ndarray:
        hood = neighbours(db, arxiv, embeddings, key, f"year <= {datasets.TRAIN_UNTIL}", NEIGHBOURS)
        top = hood[0]["similarity"]
        votes = np.full(len(classes), VOTE_FLOOR)
        for n in hood:
            votes[classes.index(n["subject"])] += np.exp(VOTE_TEMP * (n["similarity"] - top))
        return votes / votes.sum()

    cal, test = arxiv.split["valid"], arxiv.split["test"]
    return SubjectScores(
        classes=classes,
        cal_scores=np.array([scores(k) for k in cal]),
        cal_labels=np.array([classes.index(subject[k]) for k in cal]),
        test_scores=np.array([scores(k) for k in test]),
        test_labels=np.array([classes.index(subject[k]) for k in test]),
        cal_keys=cal,
        test_keys=test,
    )
scores = keystone.subject_scores(db, arxiv, propagated)
accuracy = float(np.mean(scores.test_scores.argmax(1) == scores.test_labels))
print(f"{len(scores.classes)} classes; test-era accuracy: {accuracy:.3f}")
11 classes; test-era accuracy: 0.635
claim("the nearest-neighbour vote predicts the subject well above chance",
      accuracy > 2 / len(scores.classes),
      f"accuracy {accuracy:.3f} over {len(scores.classes)} classes")
✓ the nearest-neighbour vote predicts the subject well above chance (accuracy 0.635 over 11 classes)

57.2.1 Marginal conformal holds under this shift

Marginal split-APS conformal (conformalize) takes the calibration scores, finds the finite-sample \((1-\alpha)\) APS quantile, and forms a prediction set per test paper. It is exactly valid under exchangeability.

sets = db.conformalize(
    scores.cal_scores.tolist(), scores.cal_labels.tolist(), scores.test_scores.tolist(),
    alpha=ALPHA, score="aps",
)
marg_cov = float(np.mean([y in s for y, s in zip(scores.test_labels, sets)]))
marg_size = float(np.mean([len(s) for s in sets]))
print(f"engine APS marginal coverage: {marg_cov:.3f}   (mean set size {marg_size:.2f})")
engine APS marginal coverage: 0.958   (mean set size 3.04)
band = shift.binomial_band(ALPHA, len(sets))
claim("marginal conformal coverage lands within three binomial standard errors of nominal",
      abs(marg_cov - (1 - ALPHA)) < band, f"coverage {marg_cov:.3f}, nominal {1 - ALPHA:.2f} ± {band:.3f}")
✓ marginal conformal coverage lands within three binomial standard errors of nominal (coverage 0.958, nominal 0.90 ± 0.092)

At full scale realised coverage sits at the nominal 0.90, to within sampling error: the later papers are a different population, yet the marginal quantile carries over. Exchangeability is sufficient for the guarantee, not necessary — what coverage needs is that the nonconformity score be distributed alike in the two eras, and the diagnostic below shows why it is.

57.2.2 Weighting has nothing to repair

Weighted split-conformal (Tibshirani et al. 2019) reweights the calibration nonconformity toward the test era. To compare apples to apples, shift.aps_coverage is one local APS routine used for both the marginal and the weighted pass, so the only difference between them is the weights. Its admission rule excludes the class that crosses q̂, a hair more conservative than the engine’s, so its marginal sits a little above the engine’s; the comparison that matters is between its own two passes.

local_cov, _ = shift.aps_coverage(
    scores.cal_scores, scores.cal_labels, scores.test_scores, scores.test_labels,
    weights=None, alpha=ALPHA,
)
deltas = {}
for size, weights in schemes.items():
    cov, set_size = shift.aps_coverage(
        scores.cal_scores, scores.cal_labels, scores.test_scores, scores.test_labels,
        weights=weights, alpha=ALPHA,
    )
    deltas[size] = cov - local_cov
    print(f"weighted (knn-{size:<2}) coverage {cov:.3f}   Δ {cov - local_cov:+.4f}   "
          f"set size {set_size:.2f}")
print(f"local marginal coverage          {local_cov:.3f}")
weighted (knn-10) coverage 0.958   Δ +0.0000   set size 3.04
weighted (knn-25) coverage 0.958   Δ +0.0000   set size 3.02
weighted (knn-50) coverage 0.958   Δ +0.0000   set size 3.02
local marginal coverage          0.958
max_delta = max(abs(d) for d in deltas.values())
claim("every weighting scheme moves coverage by under two points", max_delta < 0.02,
      f"largest move {max_delta:.3f}")
if SCALE is scale.Scale.FULL:
    claim("and not systematically in one direction", min(deltas.values()) < 0)
✓ every weighting scheme moves coverage by under two points (largest move 0.000)

At full scale the density ratio estimated over three neighbourhood sizes moves coverage by a point or two, in no consistent direction: there is no under-coverage to repair, and reweighting toward the test era leaves the quantile where it was.

57.2.3 Why: the shift is orthogonal to the conformal score

Weighted conformal can move the quantile only if test-era-like calibration papers have systematically different nonconformity scores.

nonconformity = shift.aps_nonconformity(scores.cal_scores, scores.cal_labels)
corr = float(np.corrcoef(nonconformity, likeness)[0, 1])
print(f"corr(nonconformity, test-likeness): {corr:+.3f}")
corr(nonconformity, test-likeness): +0.246
if SCALE is scale.Scale.FULL:
    claim("the nonconformity score barely tracks test-era likeness", abs(corr) < 0.25,
          f"correlation {corr:+.3f}")

At full scale the correlation is near zero: the time-split shift lies almost entirely orthogonal to the conformal score. That is why the marginal quantile carries over, and why reweighting cannot move it: the calibration distribution is redistributed along a direction the nonconformity barely depends on, so the weighted quantile is essentially the marginal one. The regression residual is the contrast — it does track test-era likeness, the era shifts it, and coverage breaks. Weighted conformal repairs under-coverage only when the shift is score-aligned, and fully only when the calibration set spans what the test era needs (the conformal chapter builds that case).

57.3 The honest remedy: a governed calibration cohort

If a client-side reweight cannot restore the year interval’s coverage, what does? A governed, time-aware (or simply larger) calibration cohort: choose the calibration set so it is exchangeable with the deployment era — a Mondrian or time-stratified cohort the consumer owns. The engine exposes the marginal conformalize*; the cohort is the consumer’s choice, exactly where the doctrine puts it.

db.close()

57.4 Bridge note (a signature chapter — deepened in the bridge chapters)

A prediction is a context-conditioned posterior; honest coverage needs the consumer to own the cohort. The context predictor is a Neural Process (Garnelo et al. 2018 CNP; Kim et al. 2019 ANP; the TabPFN/PFN line) — the context set is a search/walk over the citation graph. Conformal gives finite-sample coverage under exchangeability (Vovk; Angelopoulos & Bates 2021); under this dataset’s time split the regression interval under-covers while the classification set holds, as the score shift predicts (Barber et al. 2023). The textbook remedy is weighted / stratified conformal (Tibshirani et al. 2019; NAPS, Clarkson et al. 2023; CF-GNN, Huang et al. 2023) — but it repairs only a shift the nonconformity score can see. This is the tier with no monograph and no Neptune analogue — the moat.