Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): read score calibration per head on both grading sides (#101545)

posthog[bot]784aea2b3b2e
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index 66e551cfb064..e39f1385976a 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -82,7 +82,7 @@ s3://<bucket>/<prefix>/
- **A moment only takes a vector that already existed for it.** The snapshot holds the latest vector per report, and a report is re-embedded whenever its text changes (the summary workflow and every re-research run rewrite it), so the latest vector often postdates an earlier moment. Each row carries `embedding_inserted_at`, and a moment keeps the vector only when it landed at or before that snapshot's end; at the report grain the example then moves to the first snapshot where the vector was already the report's own. Without that check the family would train on text that did not exist when the report was supposedly scored. A report the snapshot has no vector for at all is not an example either, because the source table's TTL runs from report creation and a long-lived report loses its vector while still live. The scores asset records each set's coverage of the newborn pool, so a thin side input is visible rather than silent.
- **A set whose side input is unavailable is skipped, not rebuilt from nothing.** The examples asset writes no object for it, the candidate asset leaves that family's partition as it stands, and the unseen scorer drops its models for the day. Rebuilding would write an empty examples object, then an empty candidate, and the candidate's prefix cleanup would delete boosters a champion pointer can name.
- **Candidate**: one per family, per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. Each family trains on the examples of the feature set its registry entry names, and a family whose examples or metadata are missing that day is logged and skipped rather than failing the asset. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.
-- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` once per head and feature set, `inbox_ranking_candidate_trained` once per head (`head`, holdout / train AUC, average precision, logloss, positive rate, the permutation-null mean and spread, counts, `readable`) and `inbox_ranking_promotion_decided` once per run, all carrying `model_name` and `model_version` and stamped midday UTC on the partition day so re-runs and backfills chart on the day they describe. Per-head stability is a trends insight with a `head` breakdown; a readability drop is an insight alert. `metadata.json` stays the durable record. Capture is best-effort. Local dev runs (`DEBUG`) emit too, under `distinct_id` `inbox_ranking_training_local` with `environment=local`, so filter or break down on `environment` when reading the prod series; any other non-Cloud deployment emits nothing.
+- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` once per head and feature set, `inbox_ranking_candidate_trained` once per head (`head`, `model_role` always `candidate`, holdout / train AUC, average precision, logloss, positive rate, mean predicted score, the row-weighted decile calibration error, the permutation-null mean and spread, counts, `readable`), `inbox_ranking_holdout_calibration` once per head and holdout score decile and `inbox_ranking_promotion_decided` once per run, all carrying `model_name` and `model_version` and stamped midday UTC on the partition day so re-runs and backfills chart on the day they describe. Per-head stability is a trends insight with a `head` breakdown; a readability drop is an insight alert. `metadata.json` stays the durable record. Capture is best-effort. Local dev runs (`DEBUG`) emit too, under `distinct_id` `inbox_ranking_training_local` with `environment=local`, so filter or break down on `environment` when reading the prod series; any other non-Cloud deployment emits nothing.
- **Champion**: one decision per family against that family's own pointer. `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_aucs`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.
### The unseen read
@@ -91,11 +91,11 @@ The holdout grades the recipe, not the model that ships: the shipped booster is
Two assets add the missing number, an offline batch proxy for performance on reports the model never saw.
- **`inbox_ranking_unseen_scores` (dt=D)** takes the dt=D state rows of the reports **created on D**, the pool the events tag `pool=newborn`. A newborn has no scoring moment before D, and the dt=D examples stop at D minus the head's horizon (3 days at the shortest), so no example can cover it: leakage-freedom is structural, not a property of what the example builder did that day. The set difference against the examples Parquet stays as a runtime guard — a non-empty overlap fails the asset instead of publishing the number. Every newborn is scored, not a sample, with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. Every family scores the whole pool, including reports whose side input has no row for them, because grades are only comparable on paired rows; the `<set>_pool_coverage` metadata says how much of the pool each set could build a real vector for. One Parquet row per (report, model, head) carries the score, `age_hours`, `label_at_scoring` (the head outcome that had already happened when the report was scored, which for a newborn is one that landed on its own birth day, so the grade keeps it; an older pool's rows are still dropped on it, and so are a status-label head's rows in every pool, because no scores column carries the scoring-day `label_provenance_ok` that the example builder checks), `model_name`, and `pool`, the pool definition that produced the row. A re-run that scores nothing is refused when the partition already holds rows, so a day with no loadable model cannot erase the scores a later grade reads. A scores object written before `model_name` existed reads as `tabular_xgb`, the same way one written before `pool` existed keeps the old pool name.
-- **`inbox_ranking_unseen_graded` (dt=D)** reads each head's scores back from `D - horizon_days` and grades them against the dt=D labels. It keeps the rows whose cohort holds at D, reads the outcome with `Head.label`, and reports the AUC per model and head next to two comparison lines on the same rows: `recency_auc`, the AUC of ranking newest first, and `null_auc` / `null_auc_std`, the mean and spread of the AUC over seeded permutations of the scores. The mean is 0.5 by construction; the spread is the noise band a per-day AUC has to clear before a gap between two families means anything.
+- **`inbox_ranking_unseen_graded` (dt=D)** reads each head's scores back from `D - horizon_days` and grades them against the dt=D labels. It keeps the rows whose cohort holds at D, reads the outcome with `Head.label`, and reports the AUC per model and head next to two comparison lines on the same rows: `recency_auc`, the AUC of ranking newest first, and `null_auc` / `null_auc_std`, the mean and spread of the AUC over seeded permutations of the scores. The mean is 0.5 by construction; the spread is the noise band a per-day AUC has to clear before a gap between two families means anything. It also reads the calibration of those scores, which no AUC can see: the in-cohort rows are cut into score deciles by rank (`training/calibration.py`, shared with the trainer so both sides cut them the same way), and each decile's mean score is compared against the rate the outcome actually happened at. A run of equal scores stays in one decile, so a head reports fewer deciles rather than a gap that only reflects the row order. That read spans the whole pool, the reports whose side input has no row for them included, and the examples drop those rows, so on a thin `<set>_pool_coverage` day the unseen error carries a population the holdout error cannot: read the two per family.
Because the cohort, the label, the horizon and the provenance rules are the trainer's own, the unseen AUC is directly comparable to the holdout AUC of the same head and model version. The gap between the two series is the overfitting read the promotion gate cannot see.
-Three events carry it to the dashboard, next to the training events: `inbox_ranking_unseen_report_scored` per (report, model) with `p_<head>`, the raw feature inputs, and `pool` (which pool definition produced the row), `inbox_ranking_unseen_head_graded` per (model, head) with `rows`, `positives`, `birth_day_positives` (of the positives, how many landed on the report's birth day), `base_rate`, `auc` and `recency_auc`, and `inbox_ranking_unseen_report_graded` per (report, model, horizon) with `p_<head>`, `in_cohort_<head>` and `outcome_<head>` for calibration reads. Both graded events are stamped on the day the outcome was read and carry `scoring_partition`, the day the report was scored, so a chart can be built on either axis. Both also carry `pool`, read back from the scores object, so an AUC series never mixes two pool definitions: the grader reads scores from up to 14 days earlier, so the days after a pool change grade both populations. A scores object written before the column existed reads as `sampled`, the pool the old seeded sample defined.
+Four events carry it to the dashboard, next to the training events: `inbox_ranking_unseen_report_scored` per (report, model) with `p_<head>`, the raw feature inputs, and `pool` (which pool definition produced the row), `inbox_ranking_unseen_head_graded` per (model, head) with `rows`, `positives`, `birth_day_positives` (of the positives, how many landed on the report's birth day), `base_rate`, `mean_score`, `expected_calibration_error`, `auc` and `recency_auc`, `inbox_ranking_unseen_calibration` per (model, head, decile) with `bucket`, `rows`, `positives`, `mean_score` and `realized_rate` (one event per decile, because a table on the head event would be an array no insight can break down), and `inbox_ranking_unseen_report_graded` per (report, model, horizon) with `p_<head>`, `in_cohort_<head>` and `outcome_<head>` for a calibration read on the raw rows. Both graded events are stamped on the day the outcome was read and carry `scoring_partition`, the day the report was scored, so a chart can be built on either axis. Both also carry `pool`, read back from the scores object, so an AUC series never mixes two pool definitions: the grader reads scores from up to 14 days earlier, so the days after a pool change grade both populations. A scores object written before the column existed reads as `sampled`, the pool the old seeded sample defined.
### Running the training job locally
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index 29fdec9bf528..17e915e73c80 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -33,6 +33,11 @@ from products.signals.backend.ranking.features import (
)
from products.signals.dags.inbox_ranking.common import partition_object_key
from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLE
+from products.signals.dags.inbox_ranking.training.calibration import (
+ BUCKETS,
+ calibration_buckets,
+ expected_calibration_error,
+)
from products.signals.dags.inbox_ranking.training.dag import (
METADATA_FILE,
_delete_other_objects,
@@ -69,7 +74,9 @@ from products.signals.dags.inbox_ranking.training.telemetry import (
candidate_events,
capture_training_events,
examples_events,
+ holdout_calibration_events,
promotion_event,
+ unseen_calibration_events,
unseen_head_graded_events,
unseen_report_graded_events,
unseen_score_events,
@@ -86,6 +93,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
TABULAR_MODEL_NAME,
ModelFamily,
UnseenModel,
+ calibration_rows,
chance_band,
empty_scores_write_allowed,
graded_rows,
@@ -466,6 +474,10 @@ def test_train_head_keeps_logloss_on_a_single_class_holdout():
assert trained.metrics.holdout_average_precision is None
assert trained.metrics.holdout_logloss is not None and trained.metrics.holdout_logloss > 0
assert not trained.metrics.readable
+ # With no positive in the holdout, the decile error is the whole mean score.
+ assert len(trained.calibration) == BUCKETS
+ assert trained.metrics.holdout_mean_score is not None
+ assert trained.metrics.holdout_expected_calibration_error == pytest.approx(trained.metrics.holdout_mean_score)
def test_train_head_returns_none_without_both_classes():
@@ -657,6 +669,8 @@ def test_head_grades_report_counts_and_an_undefined_auc_on_a_single_class():
)
assert (single_class.rows, single_class.positives, single_class.auc) == (1, 0, None)
assert (single_class.null_auc, single_class.null_auc_std) == (None, None)
+ # No AUC, and the score gap is still readable.
+ assert (single_class.mean_score, single_class.expected_calibration_error) == (0.5, 0.5)
# Counts are ints and the undefined AUC is dropped: the graded asset writes these as Dagster
# metadata. The family is in the key, so a second family cannot overwrite the first's entries.
metadata = grade_metadata([grade])
@@ -665,6 +679,72 @@ def test_head_grades_report_counts_and_an_undefined_auc_on_a_single_class():
assert "open_tabular_xgb_candidate_auc" not in grade_metadata([single_class])
+def test_calibration_buckets_keep_a_run_of_tied_scores_in_one_bucket():
+ # Splitting a run of equal scores would give each half a realized rate that depends on the
+ # order the rows arrived in, and report a gap that is not there.
+ scores = np.array([0.1] * 8 + [1.0, 1.0])
+ outcomes = np.array([False] * 8 + [True, True])
+ buckets = calibration_buckets(outcomes, scores, buckets=5)
+ assert [(bucket.bucket, bucket.rows, bucket.realized_rate) for bucket in buckets] == [(1, 8, 0.0), (2, 2, 1.0)]
+ # Row-weighted, so the perfectly calibrated top bucket does not count for half of the error.
+ assert expected_calibration_error(buckets) == pytest.approx(0.08)
+
+
+def test_calibration_error_on_tied_scores_does_not_move_with_the_row_order():
+ # Ten of twenty reports on one score opened: that score is calibrated, however the frame is
+ # ordered. A split run would read 0.0 interleaved and 0.5 grouped.
+ tied = np.full(20, 0.5)
+ interleaved = calibration_buckets(np.array([True, False] * 10), tied)
+ grouped = calibration_buckets(np.array([True] * 10 + [False] * 10), tied)
+ assert expected_calibration_error(interleaved) == expected_calibration_error(grouped) == 0.0
+
+
+def test_calibration_buckets_fill_the_table_when_the_scores_are_distinct():
+ rng = np.random.default_rng(0)
+ scores = rng.random(100)
+ buckets = calibration_buckets(rng.random(100) < scores, scores)
+ assert len(buckets) == BUCKETS
+ assert sum(bucket.rows for bucket in buckets) == 100
+
+
+def test_calibration_reads_a_cohort_thinner_than_the_table_without_an_empty_bucket():
+ buckets = calibration_buckets(np.array([True, False]), np.array([0.7, 0.2]))
+ assert [(bucket.bucket, bucket.rows, bucket.mean_score, bucket.realized_rate) for bucket in buckets] == [
+ (1, 1, 0.2, 0.0),
+ (2, 1, 0.7, 1.0),
+ ]
+ assert expected_calibration_error(()) is None
+
+
+def test_head_grades_report_the_score_gap_a_perfect_auc_hides():
+ # Perfectly ranked and far too confident. AUC is 1.0 and says nothing about the gap, which is
+ # what a composite score over two heads runs on.
+ head = HEADS_BY_NAME["open"]
+ report_ids = [f"r{index}" for index in range(10)]
+ labels = _labels(report_ids, open_count=[1] + [0] * 9)
+ scores = _scores(report_ids, score=[0.95, *[0.5] * 9])
+ (grade,) = head_grades(
+ graded_rows(scores, labels, head, pool=POOL_NAME), head, pool=POOL_NAME, scoring_partition="2026-08-10"
+ )
+ assert grade.auc == 1.0
+ assert grade.base_rate == 0.1
+ assert grade.mean_score == pytest.approx(0.545)
+ assert grade.expected_calibration_error == pytest.approx(0.455)
+ rows = calibration_rows([grade])
+ assert [(row["bucket"], row["rows"]) for row in rows] == [(1, 9), (2, 1)]
+ assert sum(bucket.rows for bucket in grade.calibration) == grade.rows
+ assert {
+ "head": "open",
+ "model_name": TABULAR_MODEL_NAME,
+ "model_role": CANDIDATE_ROLE,
+ "pool": POOL_NAME,
+ "bucket": 2,
+ "positives": 1,
+ "mean_score": 0.95,
+ "realized_rate": 1.0,
+ }.items() <= rows[-1].items()
+
+
@pytest.mark.parametrize(
"scores,expected",
[
@@ -867,6 +947,23 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
),
*unseen_score_events(run_id="run-1", rows=score_event_rows(scores, _state(["a"]))),
*unseen_head_graded_events(run_id="run-1", grades=grades),
+ *unseen_calibration_events(run_id="run-1", rows=calibration_rows(grades)),
+ *holdout_calibration_events(
+ partition_key="2026-08-25",
+ run_id="run-1",
+ model_name=TABULAR_MODEL_NAME,
+ rows=[
+ {
+ "head": "open",
+ "calibration_buckets": BUCKETS,
+ "bucket": 10,
+ "rows": 4,
+ "positives": 2,
+ "mean_score": 0.6,
+ "realized_rate": 0.5,
+ }
+ ],
+ ),
*unseen_report_graded_events(
run_id="run-1",
rows=report_grade_rows({"open": graded}, pool=POOL_NAME, horizon_days=3, scoring_partition="2026-08-22"),
@@ -888,6 +985,8 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"inbox_ranking_promotion_decided",
"inbox_ranking_unseen_report_scored",
"inbox_ranking_unseen_head_graded",
+ "inbox_ranking_unseen_calibration",
+ "inbox_ranking_holdout_calibration",
"inbox_ranking_unseen_report_graded",
):
assert all(call["properties"]["model_name"] == TABULAR_MODEL_NAME for call in by_event[event_name])
@@ -896,6 +995,8 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
assert candidates[0]["properties"]["holdout_auc"] == 0.67
assert candidates[0]["properties"]["lookback_days"] == 60
assert candidates[0]["properties"]["trained"] is True
+ # The unseen events carry both roles, so this side needs the role to survive the same filter.
+ assert all(c["properties"]["model_role"] == CANDIDATE_ROLE for c in candidates)
assert "file" not in candidates[0]["properties"]
# A head with nothing to fit still reports, so the readability alert sees a bad day, not a gap.
assert {"trained": False, "readable": False}.items() <= candidates[2]["properties"].items()
@@ -937,7 +1038,26 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"positives": 1,
"birth_day_positives": 1,
"auc": None,
+ "mean_score": 0.8,
}.items() <= head_graded_props.items()
+ assert head_graded_props["expected_calibration_error"] == pytest.approx(0.2)
+ calibration_props = by_event["inbox_ranking_unseen_calibration"][0]["properties"]
+ assert {
+ "head": "open",
+ "scoring_partition": "2026-08-22",
+ "pool": POOL_NAME,
+ "bucket": 1,
+ "rows": 1,
+ "positives": 1,
+ "mean_score": 0.8,
+ "realized_rate": 1.0,
+ }.items() <= calibration_props.items()
+ assert set(by_event["inbox_ranking_holdout_calibration"][0]["properties"]) >= set(calibration_props) - {
+ "horizon_days",
+ "scoring_partition",
+ "pool",
+ }
+ assert by_event["inbox_ranking_holdout_calibration"][0]["properties"]["model_role"] == CANDIDATE_ROLE
report_graded_props = by_event["inbox_ranking_unseen_report_graded"][0]["properties"]
assert {
"report_id": "a",
diff --git a/products/signals/dags/inbox_ranking/training/calibration.py b/products/signals/dags/inbox_ranking/training/calibration.py
new file mode 100644
index 000000000000..a87b8e26d273
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/training/calibration.py
@@ -0,0 +1,98 @@
+"""Score calibration for the ranking heads.
+
+AUC grades the ranking and nothing else, so a head that ranks every report correctly can still
+predict 0.2 where the outcome happens on 2% of the reports. A threshold, and the composite score
+the heads exist for (a merge probability against a weighted refund penalty), only mean something
+when both sides read as probabilities. Both grading sides cut their deciles here, so the unseen
+number and the holdout number are the same measurement on two sets of rows.
+"""
+
+from collections.abc import Mapping, Sequence
+
+import numpy as np
+
+from posthog.dataclasses import frozen
+
+BUCKETS = 10
+
+
+@frozen
+class CalibrationBucket:
+ """One decile of the scores, lowest first."""
+
+ bucket: int
+ rows: int
+ positives: int
+ mean_score: float
+ realized_rate: float
+
+ def as_dict(self) -> dict[str, object]:
+ return {
+ "bucket": self.bucket,
+ "rows": self.rows,
+ "positives": self.positives,
+ "mean_score": self.mean_score,
+ "realized_rate": self.realized_rate,
+ }
+
+
+def calibration_buckets(
+ outcomes: np.ndarray, scores: np.ndarray, *, buckets: int = BUCKETS
+) -> tuple[CalibrationBucket, ...]:
+ """`scores` and `outcomes` split into at most `buckets` groups by score rank, lowest first.
+
+ The split is on rank rather than on score value because these heads score a rare outcome: most
+ reports land on a short run of near-identical low scores, and a value cut then puts most of the
+ rows in one bucket and leaves others empty.
+
+ One score can still hold more rows than a group, so every boundary moves to the end of the run
+ of equal scores it falls inside. A run split across two groups would give each of them a
+ realized rate that depends on the order the rows arrived in, and report a calibration gap that
+ is not there. Merging the run costs groups instead: a head whose scores are one value reports a
+ single bucket, and a head with fewer rows than buckets reports one bucket per row.
+ """
+ if not len(scores):
+ return ()
+ order = np.argsort(scores, kind="stable")
+ ranked = scores[order]
+ return tuple(
+ CalibrationBucket(
+ bucket=index + 1,
+ rows=len(group),
+ positives=int(outcomes[group].sum()),
+ mean_score=float(scores[group].mean()),
+ realized_rate=float(outcomes[group].mean()),
+ )
+ for index, group in enumerate(np.split(order, _bucket_edges(ranked, buckets)))
+ )
+
+
+def _bucket_edges(ranked: np.ndarray, buckets: int) -> np.ndarray:
+ """The indexes to cut `ranked`, a score column in ascending order, into near-equal groups, with
+ every cut that falls inside a run of equal scores moved to the end of that run."""
+ rows = len(ranked)
+ edges = np.unique(np.arange(1, buckets) * rows // buckets)
+ edges = edges[(edges > 0) & (edges < rows)]
+ inside_a_run = ranked[edges - 1] == ranked[edges]
+ edges = np.where(inside_a_run, np.searchsorted(ranked, ranked[edges], side="right"), edges)
+ edges = np.unique(edges)
+ return edges[edges < rows]
+
+
+def expected_calibration_error(buckets: Sequence[CalibrationBucket]) -> float | None:
+ """The row-weighted mean absolute gap between a bucket's mean score and its realized rate.
+
+ Row-weighted rather than a plain mean over buckets: the buckets are near-equal but not equal,
+ and the last one absorbs the remainder. None when there are no rows to read, so the series has
+ the same gaps as the AUC.
+ """
+ rows = sum(bucket.rows for bucket in buckets)
+ if not rows:
+ return None
+ return float(sum(bucket.rows * abs(bucket.mean_score - bucket.realized_rate) for bucket in buckets) / rows)
+
+
+def bucket_rows(buckets: Sequence[CalibrationBucket], identity: Mapping[str, object]) -> list[dict[str, object]]:
+ """One dict per bucket: what was graded, how many buckets the table holds, and the bucket's own
+ counts. Both grading sides emit these as one event per bucket, so the shape is defined once."""
+ return [{**identity, "calibration_buckets": len(buckets), **bucket.as_dict()} for bucket in buckets]
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 7ec700e95af1..73a660b6e4fc 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -90,12 +90,20 @@ from products.signals.dags.inbox_ranking.training.telemetry import (
candidate_events,
capture_training_events,
examples_events,
+ holdout_calibration_events,
promotion_event,
+ unseen_calibration_events,
unseen_head_graded_events,
unseen_report_graded_events,
unseen_score_events,
)
-from products.signals.dags.inbox_ranking.training.train import XGB_PARAMS, TrainedHead, booster_holdout_auc, train_head
+from products.signals.dags.inbox_ranking.training.train import (
+ XGB_PARAMS,
+ TrainedHead,
+ booster_holdout_auc,
+ holdout_calibration_rows,
+ train_head,
+)
from products.signals.dags.inbox_ranking.training.unseen import (
CANDIDATE_ROLE,
CHAMPION_ROLE,
@@ -103,6 +111,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
HeadGrade,
ModelFamily,
UnseenModel,
+ calibration_rows,
empty_scores_write_allowed,
graded_rows,
head_grades,
@@ -542,7 +551,19 @@ def _train_candidate(
context.log.warning(
f"removed {len(stale)} stale {family.name} objects from a previous run of dt={partition_key}"
)
- capture_training_events(context, partition_key, candidate_events(metadata))
+ capture_training_events(
+ context,
+ partition_key,
+ [
+ *candidate_events(metadata),
+ *holdout_calibration_events(
+ partition_key=partition_key,
+ run_id=context.run.run_id,
+ model_name=family.name,
+ rows=holdout_calibration_rows(trained),
+ ),
+ ],
+ )
return {
f"{family.name}_stale_objects_removed": dagster.MetadataValue.int(len(stale)),
f"{family.name}_heads_trained": dagster.MetadataValue.int(len(trained)),
@@ -934,6 +955,7 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:
partition_key,
[
*unseen_head_graded_events(run_id=context.run.run_id, grades=grades),
+ *unseen_calibration_events(run_id=context.run.run_id, rows=calibration_rows(grades)),
*unseen_report_graded_events(run_id=context.run.run_id, rows=report_rows),
],
)
diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.py
index 6024bb360be3..0856a048d99d 100644
--- a/products/signals/dags/inbox_ranking/training/telemetry.py
+++ b/products/signals/dags/inbox_ranking/training/telemetry.py
@@ -21,7 +21,7 @@ from posthog.ph_client import get_client
from products.signals.dags.inbox_ranking.common import snapshot_bounds
from products.signals.dags.inbox_ranking.training.promotion import PromotionDecision
-from products.signals.dags.inbox_ranking.training.unseen import HeadGrade
+from products.signals.dags.inbox_ranking.training.unseen import CANDIDATE_ROLE, HeadGrade
# Not a person: one fixed id for the whole dag, and no person profile is created for it. Local dev
# runs get their own id so they never blend into the prod series.
@@ -34,6 +34,8 @@ PROMOTION_DECIDED_EVENT = "inbox_ranking_promotion_decided"
UNSEEN_REPORT_SCORED_EVENT = "inbox_ranking_unseen_report_scored"
UNSEEN_HEAD_GRADED_EVENT = "inbox_ranking_unseen_head_graded"
UNSEEN_REPORT_GRADED_EVENT = "inbox_ranking_unseen_report_graded"
+UNSEEN_CALIBRATION_EVENT = "inbox_ranking_unseen_calibration"
+HOLDOUT_CALIBRATION_EVENT = "inbox_ranking_holdout_calibration"
# Candidate metadata copied onto every per-head event so a chart can filter or break down on it.
_CANDIDATE_CONTEXT_KEYS = (
@@ -67,8 +69,10 @@ class HeadExampleCounts:
def candidate_events(metadata: Mapping[str, Any]) -> list[TrainingEvent]:
"""One event per head: the head's metrics plus the candidate context. A head the candidate
could not fit still gets an event (`trained` false, `readable` false), so a per-head alert sees
- a bad day instead of a missing one."""
- context = {key: metadata.get(key) for key in _CANDIDATE_CONTEXT_KEYS}
+ a bad day instead of a missing one. The role is stamped rather than read from the metadata: this
+ asset only ever fits candidates, and the unseen events carry both roles, so without it a chart
+ filtered to the candidate keeps the unseen line and drops these rows."""
+ context = {key: metadata.get(key) for key in _CANDIDATE_CONTEXT_KEYS} | {"model_role": CANDIDATE_ROLE}
trained = [
TrainingEvent(
event=CANDIDATE_TRAINED_EVENT,
@@ -168,6 +172,36 @@ def unseen_head_graded_events(*, run_id: str, grades: Sequence[HeadGrade]) -> li
]
+def unseen_calibration_events(*, run_id: str, rows: Sequence[Mapping[str, Any]]) -> list[TrainingEvent]:
+ """One event per (model, head, score decile) of the unseen grade: how much the decile predicted
+ against how often the outcome happened. One event per bucket because a decile table on the head
+ event would be a JSON array, which no insight can break down."""
+ return [TrainingEvent(event=UNSEEN_CALIBRATION_EVENT, properties={**row, "run_id": run_id}) for row in rows]
+
+
+def holdout_calibration_events(
+ *, partition_key: str, run_id: str, model_name: str, rows: Sequence[Mapping[str, Any]]
+) -> list[TrainingEvent]:
+ """The same read on the candidate's holdout. The properties match the unseen event, so one
+ insight holds both lines and a gap between them points at holdout optimism. These rows score the
+ train-only fit and the unseen rows score the refit that ships, so the refit moves the gap too.
+ The role is stamped rather than grouped on: a run grades only the candidate it just fit, and
+ without it a chart filtered to the candidate keeps the unseen line and drops this one."""
+ return [
+ TrainingEvent(
+ event=HOLDOUT_CALIBRATION_EVENT,
+ properties={
+ "model_name": model_name,
+ "model_version": partition_key,
+ "model_role": CANDIDATE_ROLE,
+ "run_id": run_id,
+ **row,
+ },
+ )
+ for row in rows
+ ]
+
+
def unseen_report_graded_events(*, run_id: str, rows: Sequence[Mapping[str, Any]]) -> list[TrainingEvent]:
"""One event per (report, model, horizon): the scores and what actually happened, for
calibration reads. Stamped on the day the outcome was read; `scoring_partition` carries the day
diff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.py
index ffc60fb18059..a6a3872b6adf 100644
--- a/products/signals/dags/inbox_ranking/training/train.py
+++ b/products/signals/dags/inbox_ranking/training/train.py
@@ -15,6 +15,12 @@ from sklearn.metrics import average_precision_score, log_loss, roc_auc_score
from posthog.dataclasses import frozen
+from products.signals.dags.inbox_ranking.training.calibration import (
+ CalibrationBucket,
+ bucket_rows,
+ calibration_buckets,
+ expected_calibration_error,
+)
from products.signals.dags.inbox_ranking.training.examples import holdout_mask
from products.signals.dags.inbox_ranking.training.heads import Head
@@ -57,6 +63,14 @@ class HeadMetrics:
holdout_average_precision: float | None = None
holdout_logloss: float | None = None
holdout_positive_rate: float | None = None
+ # The mean predicted score next to `holdout_positive_rate`, the rate it was predicting, and the
+ # decile error between them. Both read the rows the head was capped to, and `cap_examples` keeps
+ # every positive, so a family under a row budget reports its sample's raised rate. Read per family.
+ # Both also read the train-only fit, while the candidate that ships and the unseen side grades is
+ # the refit on every row. A refit moves the predicted probabilities without moving their rank, so
+ # part of a gap to the unseen numbers is the refit rather than holdout optimism.
+ holdout_mean_score: float | None = None
+ holdout_expected_calibration_error: float | None = None
def as_dict(self) -> dict[str, object]:
return {
@@ -74,6 +88,8 @@ class HeadMetrics:
"holdout_average_precision": self.holdout_average_precision,
"holdout_logloss": self.holdout_logloss,
"holdout_positive_rate": self.holdout_positive_rate,
+ "holdout_mean_score": self.holdout_mean_score,
+ "holdout_expected_calibration_error": self.holdout_expected_calibration_error,
}
@@ -85,6 +101,9 @@ class TrainedHead:
# model on its own holdout; None when there were no holdout rows.
holdout_booster_ubj: bytes | None
metrics: HeadMetrics
+ # Beside the metrics rather than inside them: those go on one event per head, a table needs one
+ # event per bucket.
+ calibration: tuple[CalibrationBucket, ...]
def _ubj(model: xgb.XGBClassifier) -> bytes:
@@ -149,6 +168,7 @@ def train_head(
null_auc_std = float(np.std(null_aucs))
readable = _head_readable(holdout_auc, null_auc, int(y_test.sum()), min_positives=head.min_holdout_positives)
+ calibration = calibration_buckets(y_test.astype(bool), holdout_scores)
metrics = HeadMetrics(
head=head.name,
train_rows=int(len(y_train)),
@@ -166,6 +186,8 @@ def train_head(
# Logloss is defined on a single-class holdout, unlike AUC and average precision.
holdout_logloss=float(log_loss(y_test, holdout_scores, labels=[0, 1])) if len(y_test) else None,
holdout_positive_rate=float(y_test.mean()) if len(y_test) else None,
+ holdout_mean_score=float(holdout_scores.mean()) if len(y_test) else None,
+ holdout_expected_calibration_error=expected_calibration_error(calibration),
)
# Refit on everything before shipping: the holdout only exists to grade the recipe.
final = _fit(x, y, seed)
@@ -174,9 +196,16 @@ def train_head(
booster_ubj=_ubj(final),
holdout_booster_ubj=_ubj(model) if len(y_test) else None,
metrics=metrics,
+ calibration=calibration,
)
+def holdout_calibration_rows(trained: Sequence[TrainedHead]) -> list[dict[str, object]]:
+ """One dict per (head, decile) of the candidate's holdout, in the shape the unseen calibration
+ rows use, so one insight can read the holdout line and the unseen line side by side."""
+ return [row for model in trained for row in bucket_rows(model.calibration, {"head": model.head})]
+
+
def booster_holdout_auc(
booster_ubj: bytes, examples: pd.DataFrame, head: Head, *, feature_names: Sequence[str], holdout_days: int
) -> float | None:
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
index 02bd60939984..3ddb587120d7 100644
--- a/products/signals/dags/inbox_ranking/training/unseen.py
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -32,6 +32,12 @@ from products.signals.backend.ranking.features import (
feature_set_by_name,
)
from products.signals.dags.inbox_ranking.common import snapshot_bounds
+from products.signals.dags.inbox_ranking.training.calibration import (
+ CalibrationBucket,
+ bucket_rows,
+ calibration_buckets,
+ expected_calibration_error,
+)
from products.signals.dags.inbox_ranking.training.examples import birth_day_mask, point_in_time_mask, state_rows
from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head
@@ -138,6 +144,9 @@ class HeadGrade:
# outcome landed on the report's own birth day, which is where most outcomes land.
birth_day_positives: int
base_rate: float | None
+ # The mean of the scores themselves, next to `base_rate`, the rate they were predicting. AUC
+ # cannot see a gap between the two, and the composite score the heads exist for needs it closed.
+ mean_score: float | None
auc: float | None
# AUC of "newest first" on the same outcomes. A model that does not beat it has learned
# nothing the inbox could not do by sorting on age.
@@ -145,6 +154,9 @@ class HeadGrade:
# The chance line on the same rows (see ChanceBand): the band a per-day AUC has to clear.
null_auc: float | None
null_auc_std: float | None
+ # The deciles are a table, so they stay off the head event and go out one event per bucket.
+ calibration: tuple[CalibrationBucket, ...]
+ expected_calibration_error: float | None
def metrics(self) -> dict[str, int | float | None]:
return {
@@ -152,6 +164,9 @@ class HeadGrade:
"positives": self.positives,
"birth_day_positives": self.birth_day_positives,
"base_rate": self.base_rate,
+ "mean_score": self.mean_score,
+ "expected_calibration_error": self.expected_calibration_error,
+ "calibration_buckets": len(self.calibration),
"auc": self.auc,
"recency_auc": self.recency_auc,
"null_auc": self.null_auc,
@@ -159,7 +174,8 @@ class HeadGrade:
"null_permutations": NULL_PERMUTATIONS,
}
- def as_dict(self) -> dict[str, object]:
+ def identity(self) -> dict[str, object]:
+ """What was graded, without the numbers: the properties every event of this grade carries."""
return {
"head": self.head,
"horizon_days": self.horizon_days,
@@ -168,9 +184,11 @@ class HeadGrade:
"model_name": self.model_name,
"model_version": self.model_version,
"model_role": self.model_role,
- **self.metrics(),
}
+ def as_dict(self) -> dict[str, object]:
+ return {**self.identity(), **self.metrics()}
+
def _auc(outcomes: np.ndarray, scores: np.ndarray) -> float | None:
"""AUC, or None when it is undefined: a single outcome class, or a ranking column that carries
@@ -460,7 +478,13 @@ def graded_rows(head_scores: pd.DataFrame, labels: pd.DataFrame, head: Head, *,
def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partition: str) -> list[HeadGrade]:
- """The unseen read per model that scored this head, over the in-cohort rows."""
+ """The unseen read per model that scored this head, over the in-cohort rows.
+
+ Every family scores the whole pool, so a set whose side input covers few of the day's newborns
+ is graded partly on its missing branch. The example builder drops those rows, so the holdout
+ numbers never hold that population: read `mean_score` and `expected_calibration_error` per
+ `model_name`, with `<set>_pool_coverage` on the scores asset for how thin the day was.
+ """
grades: list[HeadGrade] = []
kept = graded[graded["in_cohort"]]
for (model_name, model_version, model_role), rows in kept.groupby(
@@ -470,6 +494,7 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitio
scores = rows["score"].to_numpy(dtype=float)
at_scoring = rows["label_at_scoring"].fillna(False).to_numpy(dtype=bool)
band = chance_band(outcomes, scores)
+ buckets = calibration_buckets(outcomes, scores)
grades.append(
HeadGrade(
head=head.name,
@@ -483,15 +508,27 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitio
positives=int(outcomes.sum()),
birth_day_positives=int((outcomes & at_scoring).sum()),
base_rate=float(outcomes.mean()) if len(rows) else None,
+ mean_score=float(scores.mean()) if len(rows) else None,
auc=_auc(outcomes, scores),
recency_auc=_auc(outcomes, -rows["age_hours"].to_numpy(dtype=float)),
null_auc=band.auc,
null_auc_std=band.auc_std,
+ calibration=buckets,
+ expected_calibration_error=expected_calibration_error(buckets),
)
)
return grades
+def calibration_rows(grades: Sequence[HeadGrade]) -> list[dict[str, object]]:
+ """One dict per (model, head, decile): the grade's identity plus that bucket's counts.
+
+ One event per bucket rather than a table on the head event, because a JSON array cannot be
+ charted: a reliability read is `mean_score` against `realized_rate` broken down by `bucket`.
+ """
+ return [row for grade in grades for row in bucket_rows(grade.calibration, grade.identity())]
+
+
def report_grade_rows(
graded_by_head: Mapping[str, pd.DataFrame], *, pool: str, horizon_days: int, scoring_partition: str
) -> list[dict[str, object]]: