33  In-context prediction

Train a predictor across many small tasks, then predict a row of a task it has never seen — from the task’s own rows, retrieved as context.

When to use this pattern. You have many related groups (stores, patients, products) with few rows each, and want a calibrated prediction for a new group without training a model per group.

The program is cookbook/recipes/context_predictor/example.py; its steps run here in order.

A context predictor is trained across many small tasks at once. For a target row it retrieves the target’s nearest neighbours (by embedding) from the same task, reads their outcomes, and predicts the target’s outcome as a distribution. It never trains on the task it is asked about: the task is learned from the context, in one forward pass.

import tempfile
from pathlib import Path

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq

import jammi

TASKS = 16
ROWS_PER_TASK = 24
DIM = 4

home = Path(tempfile.mkdtemp())
db = jammi.connect(f"file://{home}/engine")

33.1 A synthetic meta-dataset

16 tasks of 24 rows. Each task has its own level, and every row’s outcome y is the task’s level plus a little noise. A row’s 4-dimensional features cluster around its task’s centroid, so its nearest neighbours are rows of its own task. A predictor that learned to read the level off the context can predict rows of a task it has never seen, where the best any context-free model can do is the overall mean.

def meta_dataset(seed: int = 0) -> tuple[pa.Table, pa.Table]:
    """The source rows `(_row_id, task, y)` and their feature vectors
    `(_row_id, vector)`, keyed by one identity."""
    rng = np.random.default_rng(seed)
    ids, tasks, ys, xs = [], [], [], []
    for t in range(TASKS):
        level = rng.uniform(-3, 3)
        centroid = rng.uniform(-1, 1, DIM)
        for r in range(ROWS_PER_TASK):
            ids.append(f"t{t:02d}_r{r:02d}")
            tasks.append(f"task_{t:02d}")
            ys.append(float(level + rng.normal(0, 0.2)))
            xs.append((centroid + rng.normal(0, 0.05, DIM)).astype(np.float32))
    source = pa.table({"_row_id": ids, "task": tasks, "y": ys})
    vectors = pa.table(
        {
            "_row_id": ids,
            "vector": pa.FixedSizeListArray.from_arrays(
                pa.array(np.concatenate(xs), type=pa.float32()), DIM
            ),
        }
    )
    return source, vectors


source, vectors = meta_dataset()
pq.write_table(source, home / "rows.parquet")
pq.write_table(vectors, home / "features.parquet")
db.add_source("rows", url=str(home / "rows.parquet"), format="parquet")

33.2 Bring your own vectors

Here the features are the embedding. import_embeddings makes them the source’s embedding table, keyed like its rows, instead of computing one.

db.import_embeddings(
    source="rows",
    model="synthetic-features",
    vectors_url=str(home / "features.parquet"),
    key="_row_id",
    dimensions=DIM,
)
'rows__text_embedding__synthetic-features__20261003T074353618676165_fdd2bd59'

33.3 Meta-train

train_context_predictor is a job. It splits tasks, not rows, into train and held-out test, so the test tasks are unseen at training time; context_k is how many neighbours each prediction reads.

job = db.train_context_predictor(
    "rows",
    key_column="_row_id",
    task_column="task",
    value_column="y",
    context_k=8,
    hidden_dim=32,
    num_heads=2,
    epochs=60,
    test_task_fraction=0.25,
    seed=0,
)
job.wait()
model_id = job.output_model_id
print(f"trained {model_id}; final loss {job.metrics()['final_loss']:.3f}")
trained rows-context-predictor; final loss 0.080

33.4 Predict a task it never saw

predict_with_context_predictor returns a mean and a spread for one row, with the context rows that informed it. The rows come from the last task, held out from training, and the errors are compared with the best context-free guess, the overall mean.

truth = {r["_row_id"]: r["y"] for r in source.to_pylist()}
overall = float(np.mean(list(truth.values())))
errors, baseline = [], []
for r in range(6):
    key = f"t{TASKS - 1:02d}_r{r:02d}"
    prediction = db.predict_with_context_predictor(model_id, source="rows", target_key=key)
    mean, std = prediction["mean"], prediction["std"]
    print(
        f"{key}: y={truth[key]:+.2f}  predicted {mean:+.2f} ± {std:.2f}  "
        f"(context: {len(prediction['context_ref'])} rows, via {prediction['source']})"
    )
    errors.append(abs(mean - truth[key]))
    baseline.append(abs(overall - truth[key]))

print(
    f"mean absolute error on the held-out task: {np.mean(errors):.3f} "
    f"(overall mean as the guess: {np.mean(baseline):.3f})"
)
assert np.mean(errors) < np.mean(baseline), "the context beats no context"
t15_r00: y=+2.13  predicted +1.47 ± 0.67  (context: 8 rows, via ann)
t15_r01: y=+1.58  predicted +1.45 ± 0.71  (context: 8 rows, via ann)
t15_r02: y=+2.16  predicted +1.45 ± 0.68  (context: 8 rows, via ann)
t15_r03: y=+1.66  predicted +1.40 ± 0.69  (context: 8 rows, via ann)
t15_r04: y=+2.16  predicted +1.39 ± 0.68  (context: 8 rows, via ann)
t15_r05: y=+2.04  predicted +1.52 ± 0.67  (context: 8 rows, via ann)
mean absolute error on the held-out task: 0.512 (overall mean as the guess: 1.725)
db.close()