56  Fine-tuning an encoder on a graph

Verbs: fine_tune_graph · eval_compare · Background: representation learning on graphs — node2vec / contrastive (Stanković et al. 2020, Part III; Hamilton 2017); citation-graph contrastive supervision (SPECTER, Cohan et al. 2020); nearest-neighbor-of-own-representations (NNCLR, Dwibedi et al. 2021) · Checked: measurement (declared-edge gain, and two negative controls).

Tier 02 propagated fixed embeddings; tier 03 learns new ones. fine_tune_graph samples random walks over a graph and fine-tunes the encoder contrastively: papers that co-occur on a walk are pulled together, others pushed apart. The graph supervises the metric — but which graph matters, and this chapter measures that directly by training the identical recipe over three graphs:

import tempfile

import jammi
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from jammi_cookbook import datasets, keystone, scale
from jammi_cookbook.claims import claim

SCALE = scale.current()
db = jammi.connect(f"file://{tempfile.mkdtemp()}")
arxiv = datasets.arxiv(db, SCALE)
base = keystone.embed(db, arxiv, SCALE)
2026-10-03T07:43:35.359727Z  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"

The step, run once per graph:

def fine_tune_on_graph(
    db, arxiv: Arxiv, scale: Scale, *, provenance: str, epochs: int, **graph: str
) -> str:
    """Tier 03: fine-tune the text encoder contrastively over random walks on a
    graph of paper ids — ``edge_source=`` a registered source of ``src``/``dst``
    rows, or ``edge_graph_table=`` a ``build_neighbor_graph`` table — then embed
    every paper with the fine-tuned model. Returns the new embedding table."""
    job = db.fine_tune_graph(
        node_source=arxiv.papers,
        id_column="paper_id",
        text_column="abstract",
        base_model=encoders.text(scale),
        **graph,
        edge_provenance=provenance,
        epochs=epochs,
        batch_size=32,
        backbone_dtype=encoders.training_dtype(scale),
        walks_per_node=2,
        walk_length=4,
        sample_seed=0,
    )
    job.wait()
    return db.generate_embeddings(
        source=arxiv.papers,
        model=job.output_model_id,
        columns=["title", "abstract"],
        key="paper_id",
    )

56.1 The declared graph

declared = keystone.fine_tune_on_graph(
    db, arxiv, SCALE, edge_source=arxiv.cites, provenance="declared",
    epochs=keystone.FINE_TUNE_EPOCHS[SCALE],
)
print("fine-tuned embeddings:", declared)
fine-tuned embeddings: arxiv_papers__text_embedding__jammi_fine-tuned_890de2a6-9440-4253-ae7f-a2bdc4dc9c8c__20261003T074343001477245_c3fe0d59

56.2 The two controls

The similarity graph is the engine’s own build_neighbor_graph table over the base embeddings, which the fine-tune walks directly as edge_graph_table — the training set then pins that table by its content digest, as any derived table pins a result-table input. The random graph has as many edges as the similarity graph, drawn uniformly over the same papers, and is registered as a source.

similarity_graph = db.build_neighbor_graph(arxiv.papers, embedding_table=base, k=10, exact=True)

ids = np.array(arxiv.split["train"] + arxiv.split["valid"] + arxiv.split["test"])
n_edges = db.sql(f'SELECT COUNT(*) AS n FROM "jammi.{similarity_graph}"').to_pylist()[0]["n"]
rng = np.random.default_rng(0)
random_path = f"{tempfile.mkdtemp()}/random_edges.parquet"
pq.write_table(
    pa.table({"src": rng.choice(ids, n_edges).tolist(), "dst": rng.choice(ids, n_edges).tolist()}),
    random_path,
)
db.add_source("random_edges", url=random_path, format="parquet")

similarity = keystone.fine_tune_on_graph(
    db, arxiv, SCALE, edge_graph_table=similarity_graph, provenance="similarity",
    epochs=keystone.CONTROL_EPOCHS[SCALE],
)
random_graph = keystone.fine_tune_on_graph(
    db, arxiv, SCALE, edge_source="random_edges", provenance="declared",
    epochs=keystone.CONTROL_EPOCHS[SCALE],
)

56.3 The measurement rail: which graph supervises the metric?

One eval_compare over all four tables — the base encoder first, so every other entry carries its delta against it — on tier 01’s same-subject golden.

golden = keystone.subject_golden(db, arxiv)
compared = db.eval_compare(
    embedding_tables=[base, declared, similarity, random_graph],
    source=arxiv.papers, golden_source=golden, k=10,
)
arms = ["base", "declared", "similarity", "random"]
precision, gain = {}, {}
for arm, entry in zip(arms, compared["per_table"]):
    precision[arm] = entry["embedding_eval"]["aggregate"]["precision_at_k"]
    gain[arm] = entry["delta"]["precision_at_k"]["absolute"] if entry["delta"] else 0.0
    print(f"{arm:<11} precision@10 {precision[arm]:.3f}   Δ vs base {gain[arm]:+.3f}")
base        precision@10 0.403   Δ vs base +0.000
declared    precision@10 0.405   Δ vs base +0.002
similarity  precision@10 0.411   Δ vs base +0.008
random      precision@10 0.403   Δ vs base +0.000
if SCALE is scale.Scale.FULL:
    claim("random walks hurt, a self-similarity bootstrap helps a little, the declared graph most",
          gain["random"] < 0 < gain["similarity"] < gain["declared"],
          ", ".join(f"{arm} {gain[arm]:+.3f}" for arm in ("random", "similarity", "declared")))

At full scale the ordering is random (harmful) < base < similarity (real, partial) < declared (largest):

  • declared — the largest gain: an external signal the encoder did not already have, trained toward convergence;
  • similarity — a smaller but real gain. Training against a paper’s own nearest neighbours pulls same-subject papers closer through the same homophily mechanism nearest-neighbour contrastive learning exploits (NNCLR, Dwibedi et al. 2021; SciNCL’s citation-embedding k-NN augmentation, Ostendorff et al. 2022) — a weak bootstrap, not nothing;
  • random — harmful: training against structureless pairs degrades the metric rather than merely failing to improve it.

At small scale all three runs are two epochs on a random-weight encoder, so their numbers check the pipeline, not the finding; run this chapter at full scale to see the ordering, measured.

db.close()

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

Graph-supervised metric learning = contrastive fine-tune over walk-sampled graph edges. node2vec / DeepWalk’s skip-gram over random walks (Grover & Leskovec 2016; the monograph’s Part III graph embeddings; Hamilton et al. 2017) ↔︎ fine_tune_graph. The walk sampler turns a graph into positive pairs; the contrastive loss is the learning objective; edge_provenance names which graph — declared external structure (SPECTER, Cohan et al. 2020) supervises the largest gain, self-similarity (NNCLR, Dwibedi et al. 2021; SciNCL, Ostendorff et al. 2022) a smaller real one, and a random graph none at all.