27  Fine-tuning methods, measured side-by-side

Verbs: fine_tune (the loss / hard-negative / Matryoshka knobs) + generate_embeddings(dimensions=…) + fine_tune_graph · eval_compare · Background: contrastive metric learning — in-batch softmax (MNRL / InfoNCE, van den Oord et al. 2018), triplet margin (Schroff et al. 2015 FaceNet), CoSENT, hard-negative mining, Matryoshka representation learning (Kusupati et al. 2022) · Checked: measurement (per-method same-subject precision@10, each against the frozen base, with a paired significance test).

The case study fine-tunes the encoder over the declared citation graph and measures one gain. This chapter asks the question a practitioner asks next: of the fine-tuning methods the engine exposes, which should I reach for? The task is fixed — same-subject retrieval over the papers, scored against the papers’ same-subject golden — and the method varies: the contrastive loss, hard-negative mining, the Matryoshka nesting, and, for contrast, the declared-citation graph fine-tune. Every method is the same short LoRA run on the same base encoder over the same supervision, so the only thing that varies is the method.

import tempfile
from pathlib import Path

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

SCALE = scale.current()
BASE = encoders.text(SCALE)
EPOCHS = {scale.Scale.SMALL: 2, scale.Scale.FULL: 3}[SCALE]
db = jammi.connect(f"file://{tempfile.mkdtemp()}")
arxiv = datasets.arxiv(db, SCALE)
raw = keystone.embed(db, arxiv, SCALE)
golden = keystone.subject_golden(db, arxiv)
2026-10-03T07:42:36.139597Z  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"

27.1 The supervision

fine_tune reads its supervision from a source’s columns, and the columns’ shape names the objective: pairs (anchor, positive), triplets (anchor, positive, negative), or graded pairs (text_a, text_b, score). We mine all three from one signal — the training-era papers’ subjects: a paper’s positive is the next paper of its subject, its negative the next paper of another. It is the same signal the retrieval target scores, so a gain is a genuine metric-learning gain on subject supervision.

train = db.sql(
    f"SELECT paper_id, abstract, subject FROM {arxiv.papers}.public.{arxiv.papers} "
    f"WHERE year <= {datasets.TRAIN_UNTIL} ORDER BY paper_id"
).to_pylist()
by_subject: dict[str, list[dict]] = {}
for p in train:
    by_subject.setdefault(p["subject"], []).append(p)
anchors = [p for p in train if len(by_subject[p["subject"]]) > 1]


def positive(p):
    peers = by_subject[p["subject"]]
    return peers[(peers.index(p) + 1) % len(peers)]["abstract"]


def negative(p, i):
    return next(q for q in train[i + 1:] + train if q["subject"] != p["subject"])["abstract"]


work = Path(tempfile.mkdtemp())


def supervision(name: str, columns: dict) -> str:
    pq.write_table(pa.table(columns), work / f"{name}.parquet")
    db.add_source(name, url=str(work / f"{name}.parquet"), format="parquet")
    return name


pairs = supervision("pairs", {
    "anchor": [p["abstract"] for p in anchors],
    "positive": [positive(p) for p in anchors],
})
triplets = supervision("triplets", {
    "anchor": [p["abstract"] for p in anchors],
    "positive": [positive(p) for p in anchors],
    "negative": [negative(p, train.index(p)) for p in anchors],
})
graded = supervision("graded", {
    "text_a": [p["abstract"] for p in anchors] * 2,
    "text_b": [positive(p) for p in anchors] + [negative(p, train.index(p)) for p in anchors],
    "score": [1.0] * len(anchors) + [0.0] * len(anchors),
})
print(f"{len(anchors)} training-era anchors → pairs, triplets, graded pairs")
180 training-era anchors → pairs, triplets, graded pairs

27.2 The method spectrum

One function runs a method: a LoRA fine-tune of the base encoder on a supervision source, then every paper embedded with the result. The methods differ only in the source and the knobs.

width = len(db.encode_query(model=BASE, query="a probe"))


def tuned(source: str, columns: list[str], **knobs) -> str:
    """The fine-tuned model's id."""
    job = db.fine_tune(
        source=source, base_model=BASE, columns=columns, method="lora",
        task="text_embedding", epochs=EPOCHS, batch_size=16, max_seq_length=128,
        backbone_dtype=encoders.training_dtype(SCALE), seed=0, **knobs,
    )
    job.wait()
    return job.output_model_id


def embedded(model: str, dimensions: int | None = None) -> str:
    """Every paper embedded by `model`, at `dimensions` or the model's width."""
    return db.generate_embeddings(
        source=arxiv.papers, model=model, columns=["title", "abstract"],
        key="paper_id", dimensions=dimensions,
    )


models = {
    "mnrl": tuned(pairs, ["anchor", "positive"], embedding_loss="mnrl"),
    "mnrl_t50": tuned(pairs, ["anchor", "positive"], embedding_loss="mnrl", mnrl_temperature=50.0),
    "triplet": tuned(triplets, ["anchor", "positive", "negative"], embedding_loss="triplet"),
    "cosent": tuned(graded, ["text_a", "text_b", "score"], embedding_loss="cosent"),
    "hard_neg": tuned(pairs, ["anchor", "positive"], embedding_loss="mnrl",
                      mine_hard_negatives=True, hard_negative_k=5),
    "matryoshka": tuned(pairs, ["anchor", "positive"], embedding_loss="mnrl",
                        matryoshka_dims=[width, width // 2, width // 4]),
}
methods = {name: embedded(model) for name, model in models.items()}
methods["graph"] = keystone.fine_tune_on_graph(
    db, arxiv, SCALE, edge_source=arxiv.cites, provenance="declared", epochs=EPOCHS,
)

27.3 The measurement

One eval_compare scores the base and every method on the same golden, and reports each method’s difference from the base with a paired significance test over the queries.

compared = db.eval_compare(
    embedding_tables=[raw, *methods.values()], source=arxiv.papers,
    golden_source=golden, k=10,
)
base = compared["per_table"][0]["embedding_eval"]["aggregate"]["precision_at_k"]
results = {}
print(f"{'method':<12}{'precision@10':>14}{'Δ vs base':>11}{'95% CI':>20}")
print(f"{'(base)':<12}{base:>14.3f}")
for name, entry in zip(methods, compared["per_table"][1:]):
    delta = entry["delta"]["precision_at_k"]
    ci = entry["delta"]["significance"]["precision_at_k"]
    results[name] = entry["embedding_eval"]["aggregate"]["precision_at_k"]
    print(f"{name:<12}{results[name]:>14.3f}{delta['absolute']:>+11.3f}"
          f"{ci['ci_lower']:>+10.3f} … {ci['ci_upper']:+.3f}")
method        precision@10  Δ vs base              95% CI
(base)               0.403
mnrl                 0.404     +0.000    -0.002 … +0.003
mnrl_t50             0.404     +0.000    -0.002 … +0.003
triplet              0.403     +0.000    -0.003 … +0.003
cosent               0.402     -0.001    -0.004 … +0.002
hard_neg             0.404     +0.000    -0.002 … +0.003
matryoshka           0.404     +0.001    -0.001 … +0.004
graph                0.405     +0.002    -0.003 … +0.006
claim("each method's delta is its precision@10 less the base's",
      all(abs(entry["delta"]["precision_at_k"]["absolute"] - (results[name] - base)) < 1e-9
          for name, entry in zip(methods, compared["per_table"][1:])))
✓ each method's delta is its precision@10 less the base's

27.4 Reading the spectrum

significant = [
    name for name, entry in zip(methods, compared["per_table"][1:])
    if entry["delta"]["significance"]["precision_at_k"]["ci_lower"] > 0
]
spread = max(results.values()) - min(results.values())
print(f"spread across the methods:         {spread:.3f}")
print(f"methods whose gain excludes zero:  {significant or 'none'}")
claim("the losses barely differ: one supervision, different negative policies", spread < 0.05,
      f"spread {spread:.3f}")
spread across the methods:         0.003
methods whose gain excludes zero:  none
✓ the losses barely differ: one supervision, different negative policies (spread 0.003)

A method earns a verdict only when its confidence interval excludes zero; a difference inside the interval is not evidence of a better method, however the point estimates sort. Three things hold whatever the ranking:

  • The losses are one objective with different negative policies. MNRL is in-batch softmax over positives; triplet is the same pull-together / push-apart with an explicit margin and a chosen negative; hard-negative mining changes which negatives the batch sees; CoSENT learns from graded pairs. When the supervision already agrees with the base geometry, no choice among them has much headroom — the supervision, not the loss, is the lever.
  • The graph fine-tune is a different supervision, not a better loss. It learns who-cited-whom, a signal the text cannot reconstruct; it is scored on the same target for contrast.
  • Matryoshka is a nesting constraint, not a new loss. It trains the leading coordinates to be an embedding on their own; its full-width precision is measured above, and what the constraint buys is measured next.

27.5 Serving a Matryoshka prefix

generate_embeddings(dimensions=d) serves a model’s leading d coordinates, each vector renormalised to unit length — an index a half or a quarter the size. eval_compare encodes each query at its table’s width, so every table below is scored as it would be searched. The Matryoshka model was trained for these prefixes; the plain MNRL model, from the same pairs and budget, was not.

widths = [width, width // 2, width // 4]
served = {name: [embedded(models[name], w) for w in widths] for name in ("mnrl", "matryoshka")}
by_width = db.eval_compare(
    embedding_tables=[table for tables in served.values() for table in tables],
    source=arxiv.papers, golden_source=golden, k=10,
)
scores = iter(e["embedding_eval"]["aggregate"]["precision_at_k"] for e in by_width["per_table"])
prefix = {name: dict(zip(widths, scores)) for name in served}
print(f"{'model':<12}" + "".join(f"{f'{w} dims':>11}" for w in widths))
for name, row in prefix.items():
    print(f"{name:<12}" + "".join(f"{row[w]:>11.3f}" for w in widths))
model           32 dims    16 dims     8 dims
mnrl              0.404      0.381      0.380
matryoshka        0.404      0.381      0.380
claim("a quarter-width index keeps at least 90% of the full width's precision@10",
      all(row[widths[-1]] >= 0.9 * row[widths[0]] for row in prefix.values()),
      ", ".join(f"{name} {row[widths[-1]]:.3f} of {row[widths[0]]:.3f}" for name, row in prefix.items()))
✓ a quarter-width index keeps at least 90% of the full width's precision@10 (mnrl 0.380 of 0.404, matryoshka 0.380 of 0.404)

Read each row left to right: how much retrieval quality a model keeps as its index shrinks. A model trained without the nesting constraint spreads its information over every coordinate, so a prefix of it is only an accident of its basis; the Matryoshka model’s leading coordinates were optimised to stand alone at each trained width. The difference between the two rows at the narrowest width is the index-size saving the constraint pays for.

db.close()

27.6 Bridge note

The contrastive losses are one objective with different negative policies. MNRL / InfoNCE (van den Oord et al. 2018) is in-batch softmax over positives; triplet margin (Schroff et al. 2015) is the same pull-together/push-apart with an explicit margin and chosen negatives; hard-negative mining changes which negatives, not the objective; CoSENT scores graded pairs. Matryoshka (Kusupati et al. 2022) is orthogonal — a nesting constraint on the representation. A paired significance test, not a sorted table, says whether a method is better.