: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): add within-team auc to inbox ranking evaluation (#116265)
posthog[bot]dfb7e67a29d4
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 2c924d956df4..c7f17b6480e4 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -268,6 +268,17 @@ At the full horizon, the cohort, label and provenance rules are the trainer's owThe event names keep the `unseen` prefix so existing dashboard tiles keep reading. Three events carry the baked results, next to the daily `inbox_ranking_unseen_head_evaluated`: `inbox_ranking_unseen_head_graded` per (model, head) with `readable` (whether the head's holdout could be read on the model that wrote the scores), `model_role`, `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 the longest head horizon (21 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.+#### Pooled and within-team AUC++The inbox sorts the reports of one team, so the order that matters is the order inside one team. Every grade reports two AUCs on the same rows, and each answers a different question:++- **Pooled AUC** (`holdout_auc` on a candidate, `auc` and `recency_auc` on the online grade) compares every report with every other report, across teams. It asks: does the model separate the reports that get the outcome from the reports that do not, anywhere? A model that only learns which teams engage a lot gains pooled AUC. A score equal to each team's past label rate gets a pooled AUC well above 0.5.+- **Within-team AUC** (`holdout_within_team_auc` on a candidate, `within_team_auc` and `recency_within_team_auc` on the online grade) compares only two reports of the same team. It asks: inside one inbox, does a report that gets the outcome rank above one that does not? The team-rate score gets exactly 0.5 here.++`within_team_auc` weighs each team by its positive x negative pairs, so a large team counts more. `within_team_auc_macro` is the mean of the per-team AUCs, so each team counts the same. `within_team_teams` and `within_team_pairs` say how much the number rests on. A team with one outcome class has no pair and adds nothing, and a row without a team id is left out of these four fields only. Both AUCs are null when no team has both classes.++Compare model families on the within-team AUC when they differ in team-level inputs, such as project vectors: a gain in pooled AUC alone can be team identity rather than a better order. The promotion gate still reads the pooled holdout AUC.+#### Reading one rendering against anotherThe `title_embeddings` and `report_embeddings` families are trained and graded to be compared, not promoted. The read:@@ -324,7 +335,7 @@ Nothing here touches the prod bucket: the reader credential is read-only and theDEBUG=1 python -m products.signals.dags.inbox_ranking.multihead --output multihead.json```-The run takes the newest day that has the state, labels and report embeddings cached, unless you pass `--partition`. It builds the `open`, `action` and `fixed` examples with the training dag's own `example_moments`, `cap_examples` and `holdout_mask`. Then it prints AUC, average precision and ECE per head for three models on each head's own holdout rows:+The run takes the newest day that has the state, labels and report embeddings cached, unless you pass `--partition`. It builds the `open`, `action` and `fixed` examples with the training dag's own `example_moments`, `cap_examples` and `holdout_mask`. Then it prints pooled AUC, within-team AUC (`team_auc`), average precision and ECE per head for three models on each head's own holdout rows:- `champion_recipe` is the `XGB_PARAMS` booster, refit on the head's train rows.- `nn_report` is the network over the report vector only.diff --git a/products/signals/dags/inbox_ranking/multihead/prototype.py b/products/signals/dags/inbox_ranking/multihead/prototype.pyindex 349c1a678928..c0d28b49ea99 100644--- a/products/signals/dags/inbox_ranking/multihead/prototype.py+++ b/products/signals/dags/inbox_ranking/multihead/prototype.py@@ -50,6 +50,7 @@ from products.signals.dags.inbox_ranking.training.calibration import calibrationfrom products.signals.dags.inbox_ranking.training.examples import Snapshot, cap_examples, example_moments, holdout_maskfrom products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Headfrom products.signals.dags.inbox_ranking.training.train import XGB_PARAMS+from products.signals.dags.inbox_ranking.training.within_team import within_team_aucPROTOTYPE_HEADS: tuple[Head, ...] = tuple(HEADS_BY_NAME[name] for name in ("open", "action", "fixed"))FEATURE_SET = REPORT_EMBEDDINGS_FEATURE_SET@@ -81,6 +82,9 @@ class ExampleTable:in_holdout = self.holdout[:, head_index]return np.flatnonzero(observed & (in_holdout if holdout else ~in_holdout))+ def team_ids(self, rows: np.ndarray) -> np.ndarray:+ return self.rows["report_team_id"].to_numpy(dtype=object)[rows]+def example_table(snapshots: Mapping[datetime.date, Snapshot], extras: Extras, *, holdout_days: int) -> ExampleTable:"""The moments of every prototype head, joined on the report moment."""@@ -162,6 +166,9 @@ class HeadScore:holdout_rows: intholdout_positives: intauc: float | None+ # The AUC over pairs inside one team. A model that only learns which teams engage a lot+ # gains pooled `auc` and none of this.+ within_team_auc: float | Noneaverage_precision: float | Noneexpected_calibration_error: float | None@@ -172,13 +179,15 @@ class HeadScore:"holdout_rows": self.holdout_rows,"holdout_positives": self.holdout_positives,"auc": self.auc,+ "within_team_auc": self.within_team_auc,"average_precision": self.average_precision,"expected_calibration_error": self.expected_calibration_error,}-def grade(model: str, head: str, outcomes: np.ndarray, scores: np.ndarray) -> HeadScore:- """AUC, average precision and ECE, with the same decile cut the training dag grades on."""+def grade(model: str, head: str, outcomes: np.ndarray, scores: np.ndarray, team_ids: np.ndarray) -> HeadScore:+ """Pooled and within-team AUC, average precision and ECE, with the same decile cut the training+ dag grades on."""positives = int(outcomes.sum())two_classes = 0 < positives < len(outcomes)return HeadScore(@@ -187,6 +196,7 @@ def grade(model: str, head: str, outcomes: np.ndarray, scores: np.ndarray) -> Heholdout_rows=len(outcomes),holdout_positives=positives,auc=float(roc_auc_score(outcomes, scores)) if two_classes else None,+ within_team_auc=within_team_auc(outcomes, scores, team_ids).auc,average_precision=float(average_precision_score(outcomes, scores)) if two_classes else None,expected_calibration_error=expected_calibration_error(calibration_buckets(outcomes.astype(bool), scores)),)@@ -204,7 +214,15 @@ def champion_recipe_scores(table: ExampleTable, reports: np.ndarray, *, seed: incontinuemodel = xgb.XGBClassifier(**XGB_PARAMS, random_state=seed)model.fit(reports[train], y_train, verbose=False)- scores.append(grade(CHAMPION_RECIPE, head.name, y_test, model.predict_proba(reports[test])[:, 1]))+ scores.append(+ grade(+ CHAMPION_RECIPE,+ head.name,+ y_test,+ model.predict_proba(reports[test])[:, 1],+ table.team_ids(test),+ )+ )return scores@@ -225,7 +243,9 @@ def network_scores(if len(test) == 0:continuepredicted = network.predict(inputs, test)[:, head_index]- scores.append(grade(name, head.name, table.labels[test, head_index].astype(int), predicted))+ scores.append(+ grade(name, head.name, table.labels[test, head_index].astype(int), predicted, table.team_ids(test))+ )return scores, losses@@ -286,14 +306,14 @@ def format_scores(scores: Sequence[HeadScore]) -> str:def number(value: float | None) -> str:return "-" if value is None else f"{value:.3f}"- header = f"{'head':<8}{'model':<20}{'rows':>8}{'pos':>7}{'auc':>8}{'ap':>8}{'ece':>8}"+ header = f"{'head':<8}{'model':<20}{'rows':>8}{'pos':>7}{'auc':>8}{'team_auc':>10}{'ap':>8}{'ece':>8}"lines = [header, "-" * len(header)]order = {name: index for index, name in enumerate((CHAMPION_RECIPE, *ABLATIONS))}for head in PROTOTYPE_HEADS:for score in sorted((s for s in scores if s.head == head.name), key=lambda s: order.get(s.model, 99)):lines.append(f"{score.head:<8}{score.model:<20}{score.holdout_rows:>8}{score.holdout_positives:>7}"- f"{number(score.auc):>8}{number(score.average_precision):>8}"+ f"{number(score.auc):>8}{number(score.within_team_auc):>10}{number(score.average_precision):>8}"f"{number(score.expected_calibration_error):>8}")return "\n".join(lines)diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex ded1c5bf3b8f..8f8fe1ac825a 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -15,6 +15,7 @@ import xgboost as xgbimport pyarrow.parquet as pqfrom botocore.exceptions import ClientErrorfrom pydantic import ValidationError+from sklearn.metrics import roc_auc_scorefrom posthog import settings@@ -160,6 +161,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (unseen_pool,with_model_names,)+from products.signals.dags.inbox_ranking.training.within_team import NO_TEAMS, WithinTeamAuc, within_team_aucEMBEDDINGS_MODEL_NAME = REPORT_EMBEDDINGS_MODEL_NAME# The two renderings' sets. Every rule about a vector holds for both, because they are one class@@ -254,7 +256,7 @@ def test_build_examples_is_a_scoring_moment_with_a_future_label():open_head = HEADS_BY_NAME["open"]later = D0 + datetime.timedelta(days=open_head.horizon_days)ids = ["a", "b", "c", "d"]- state = _state(ids, report_created_at=[BEFORE_THE_WINDOW] * 4)+ state = _state(ids, report_created_at=[BEFORE_THE_WINDOW] * 4, report_team_id=[1, 1, 2, None])snapshots = {# a: not yet impressed or opened at D0, impressed and opened by D0+3 -> positive;# b: already opened at D0 -> excluded; c: never opened -> negative;@@ -275,6 +277,7 @@ def test_build_examples_is_a_scoring_moment_with_a_future_label():examples = build_examples(snapshots, open_head, _at_grain(STATE_FEATURE_SET, SCORING_MOMENT_GRAIN))assert list(examples.columns) == list(example_columns(STATE_FEATURE_SET))assert examples.set_index("report_id")["label"].to_dict() == {"a": 1, "c": 0, "d": 1}+ assert examples.set_index("report_id")["team_id"].fillna(-1).to_dict() == {"a": 1, "c": 2, "d": -1}assert (examples["snapshot_date"] == D0).all()assert (examples["age_hours"] == 12.0).all()@@ -584,6 +587,7 @@ def test_train_head_learns_a_separable_signal_and_names_its_features():examples.insert(1, "report_id", [f"r{i}" for i in range(n)])examples.insert(2, "snapshot_date", D0)examples.insert(3, "report_created_at", created)+ examples.insert(4, "team_id", rng.integers(1, 4, n))examples["label"] = (signal_count > 25).astype(int)trained = train_head(examples, head, feature_names=STATE_FEATURE_SET.feature_names, holdout_days=7)@@ -607,8 +611,11 @@ def test_train_head_learns_a_separable_signal_and_names_its_features():assert sum(count or 0 for count in counts) == trained.metrics.holdout_rowsassert holdout.precision is not None and holdout.precision > 0.8assert holdout.recall is not None and holdout.recall > 0.8+ within_team = trained.metrics.holdout_within_team+ assert within_team.teams == 3 and within_team.auc is not None and within_team.auc > 0.9metadata_head = trained.metrics.as_dict()assert metadata_head["holdout_classification_threshold"] == holdout.threshold+ assert metadata_head.items() >= within_team.as_dict(prefix="holdout_").items()assert classification_thresholds({"heads": [metadata_head]}) == {head.name: trained.metrics.refit_classification_threshold}@@ -954,6 +961,42 @@ def test_grading_a_status_label_head_drops_a_newborn_outcome_from_the_scoring_daassert graded["in_cohort"].to_dict() == {"a": True, "b": False}+ "outcomes,scores,team_ids,expected",+ [+ # Team 3 has no positive, so it adds no team and no pair, whatever its scores.+ (+ [1, 0, 0, 0, 0, 0],+ [0.9, 0.1, 0.1, 0.1, 0.99, 0.0],+ [1, 1, 1, 1, 3, 3],+ WithinTeamAuc(auc=1.0, macro=1.0, teams=1, pairs=3),+ ),+ # Team 1 ranks its one pair right, team 2 ranks its four pairs wrong.+ (+ [1, 0, 1, 1, 0, 0],+ [0.9, 0.1, 0.1, 0.2, 0.8, 0.9],+ [1, 1, 2, 2, 2, 2],+ WithinTeamAuc(auc=0.2, macro=0.5, teams=2, pairs=5),+ ),+ # A row without a team is left out, even when it would make a pair.+ ([1, 0, 0], [0.9, 0.1, 0.95], [1, 1, None], WithinTeamAuc(auc=1.0, macro=1.0, teams=1, pairs=1)),+ ([1, 0], [0.9, float("nan")], [1, 1], NO_TEAMS),+ ],+)+def test_within_team_auc_counts_only_pairs_inside_one_team(outcomes, scores, team_ids, expected):+ result = within_team_auc(np.array(outcomes), np.array(scores), np.array(team_ids, dtype=object))+ assert result.as_dict() == pytest.approx(expected.as_dict())+++def test_within_team_auc_gives_chance_to_a_team_base_rate_that_pooled_auc_rewards():+ outcomes = np.array([1, 0, 0, 0, 1, 1, 1, 0])+ base_rates = np.array([0.25] * 4 + [0.75] * 4)+ assert roc_auc_score(outcomes, base_rates) > 0.5+ assert within_team_auc(outcomes, base_rates, np.array([1] * 4 + [2] * 4)) == WithinTeamAuc(+ auc=0.5, macro=0.5, teams=2, pairs=6+ )++def test_head_grades_report_counts_and_an_undefined_auc_on_a_single_class():head = HEADS_BY_NAME["open"]labels = _labels(["a", "e"], open_count=[1, 0])@@ -976,6 +1019,8 @@ def test_head_grades_report_counts_and_an_undefined_auc_on_a_single_class():)assert newest_first.recency_auc == 1.0assert grade.null_auc is not None+ assert (grade.within_team.auc, grade.within_team.pairs) == (1.0, 1)+ assert grade.as_dict()["recency_within_team_auc"] == 0.5# A head with rows but one outcome class still reports, so the daily series has no gap.(single_class,) = head_grades(graded_rows(_scores(["e"], model_version=["2026-08-11"]), _labels(["e"], open_count=[0]), head, pool=POOL_NAME),@@ -2141,7 +2186,15 @@ def test_build_examples_carries_the_columns_of_the_set_it_is_given():later: Snapshot(date=later, state=_state(ids), labels=_labels(ids, open_count=[2])),}examples = build_examples(snapshots, HEADS_BY_NAME["open"], _AgeOnlyFeatureSet())- assert list(examples.columns) == ["head", "report_id", "snapshot_date", "report_created_at", "age_hours", "label"]+ assert list(examples.columns) == [+ "head",+ "report_id",+ "snapshot_date",+ "report_created_at",+ "team_id",+ "age_hours",+ "label",+ ]assert examples["age_hours"].tolist() == [12.0]diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex beab617bf559..964f3fe403dd 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -701,6 +701,14 @@ def _train_candidate(for head in trainedif head.metrics.holdout_auc is not None},+ **{+ f"{family.name}_{head.head}_{name}": (+ dagster.MetadataValue.int(value) if isinstance(value, int) else dagster.MetadataValue.float(value)+ )+ for head in trained+ for name, value in head.metrics.holdout_within_team.as_dict(prefix="holdout_").items()+ if value is not None+ },f"{family.name}_s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{metadata_key}"),}diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.pyindex 7391c19d2204..4dde0ccb2b7f 100644--- a/products/signals/dags/inbox_ranking/training/examples.py+++ b/products/signals/dags/inbox_ranking/training/examples.py@@ -64,14 +64,16 @@ def state_columns(feature_set: FeatureSet) -> tuple[str, ...]:return (*BASE_STATE_COLUMNS, *(name for name in feature_set.state_columns if name not in BASE_STATE_COLUMNS))-# The moment spine, before any feature set's columns are added to it.-MOMENT_COLUMNS = ("head", "report_id", "snapshot_date", "report_created_at", "label")+# The moment spine, before any feature set's columns are added to it. `team_id` is the report's team+# on the moment's snapshot. No feature set reads it: the trainer reads it to grade the order inside+# one team.+MOMENT_COLUMNS = ("head", "report_id", "snapshot_date", "report_created_at", "team_id", "label")def example_columns(feature_set: FeatureSet) -> tuple[str, ...]:"""The examples Parquet columns for `feature_set`. One object per set, because two sets carrydifferent feature columns."""- return ("head", "report_id", "snapshot_date", "report_created_at", *feature_set.feature_names, "label")+ return (*MOMENT_COLUMNS[:-1], *feature_set.feature_names, MOMENT_COLUMNS[-1])def state_rows(state: pd.DataFrame, feature_set: FeatureSet) -> pd.DataFrame:@@ -330,6 +332,7 @@ def example_moments("report_id": kept_ids.to_numpy(),"snapshot_date": date,"report_created_at": pd.to_datetime(state.loc[kept_ids, "report_created_at"], utc=True).to_numpy(),+ "team_id": _team_ids(state, kept_ids),"label": head.label(labels_later.loc[kept_ids]).astype(int).to_numpy(),})@@ -339,6 +342,12 @@ def example_moments(return pd.concat(frames, ignore_index=True)+def _team_ids(state: pd.DataFrame, ids: pd.Index) -> pd.api.extensions.ExtensionArray:+ if "report_team_id" not in state:+ return pd.array([None] * len(ids), dtype="Int64")+ return pd.to_numeric(state.loc[ids, "report_team_id"], errors="coerce").astype("Int64").array++def birth_day_positives(examples: pd.DataFrame) -> int:"""How many of `examples`' positives sit on their report's birth day: the size of what thebirth-day rule keeps. Read off the moment columns, so a wide set does not copy its featurediff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.pyindex 90173945c697..33bdbee9c03d 100644--- a/products/signals/dags/inbox_ranking/training/train.py+++ b/products/signals/dags/inbox_ranking/training/train.py@@ -28,6 +28,7 @@ from products.signals.dags.inbox_ranking.training.classification import ()from products.signals.dags.inbox_ranking.training.examples import holdout_maskfrom products.signals.dags.inbox_ranking.training.heads import Head+from products.signals.dags.inbox_ranking.training.within_team import NO_TEAMS, WithinTeamAuc, within_team_aucXGB_PARAMS: dict[str, object] = {"n_estimators": 200,@@ -81,6 +82,9 @@ class HeadMetrics:# The positive rate of every row the refit that ships was fit on. The unseen grades of this# model read it as their threshold, so it is saved here rather than derived from the unseen rows.refit_classification_threshold: float | None = None+ # The holdout AUC over pairs inside one team only. The promotion gate keeps reading the pooled+ # `holdout_auc`.+ holdout_within_team: WithinTeamAuc = NO_TEAMSdef as_dict(self) -> dict[str, object]:return {@@ -90,6 +94,7 @@ class HeadMetrics:"holdout_rows": self.holdout_rows,"holdout_positives": self.holdout_positives,"holdout_auc": self.holdout_auc,+ **self.holdout_within_team.as_dict(prefix="holdout_"),"null_auc": self.null_auc,"null_auc_std": self.null_auc_std,"null_permutations": NULL_PERMUTATIONS,@@ -134,6 +139,14 @@ def _auc(y: np.ndarray, scores: np.ndarray) -> float | None:return float(roc_auc_score(y, scores))+def _team_ids(rows: pd.DataFrame) -> np.ndarray:+ """Each row's team, None where unknown. An examples object written before the column existed+ has no team, so its within-team fields stay empty."""+ if "team_id" not in rows:+ return np.full(len(rows), None, dtype=object)+ return rows["team_id"].to_numpy(dtype=object)++def _head_readable(holdout_auc: float | None, null_auc: float | None, holdout_positives: int, *, min_positives: int) -> bool:@@ -203,6 +216,7 @@ def train_head(holdout_expected_calibration_error=expected_calibration_error(calibration),holdout_classification=classification_metrics(y_test, holdout_scores, float(y_train.mean())),refit_classification_threshold=float(y.mean()),+ holdout_within_team=within_team_auc(y_test, holdout_scores, _team_ids(rows)[test]),)# Refit on everything before shipping: the holdout only exists to grade the recipe.final = _fit(x, y, seed)diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex bb29ef45225e..79367de7dfb0 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -40,6 +40,7 @@ from products.signals.dags.inbox_ranking.training.classification import ()from products.signals.dags.inbox_ranking.training.examples import birth_day_mask, point_in_time_maskfrom products.signals.dags.inbox_ranking.training.heads import Head+from products.signals.dags.inbox_ranking.training.within_team import NO_TEAMS, WithinTeamAuc, within_team_auc# Stamped on every scored event, so a chart can tell this pool definition from a later one.POOL_NAME = "newborn"@@ -156,6 +157,10 @@ class HeadGrade:# The in-cohort rows at the threshold of the model that wrote the scores, so an early and a# mature grade of one cohort use the same cut.classification: ClassificationMetrics = UNKNOWN_THRESHOLD+ # `auc` and `recency_auc` over the pairs inside one team only. A row without a team id is left+ # out of these and kept in every other field.+ within_team: WithinTeamAuc = NO_TEAMS+ recency_within_team: WithinTeamAuc = NO_TEAMSdef metrics(self) -> dict[str, int | float | None]:return {@@ -168,6 +173,8 @@ class HeadGrade:"calibration_buckets": len(self.calibration),"auc": self.auc,"recency_auc": self.recency_auc,+ **self.within_team.as_dict(),+ **self.recency_within_team.as_dict(prefix="recency_"),"null_auc": self.null_auc,"null_auc_std": self.null_auc_std,"null_permutations": NULL_PERMUTATIONS,@@ -389,6 +396,8 @@ def head_grades(outcomes = rows["outcome"].to_numpy(dtype=bool)scores = rows["score"].to_numpy(dtype=float)at_scoring = rows["label_at_scoring"].fillna(False).to_numpy(dtype=bool)+ team_ids = rows["team_id"].to_numpy(dtype=object)+ newest_first = _newest_first(rows)band = chance_band(outcomes, scores)buckets = calibration_buckets(outcomes, scores)grades.append(@@ -408,13 +417,15 @@ def head_grades(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, _newest_first(rows)),+ recency_auc=_auc(outcomes, newest_first),null_auc=band.auc,null_auc_std=band.auc_std,calibration=buckets,expected_calibration_error=expected_calibration_error(buckets),# Read from every scored row, so an empty cohort still reports its threshold.classification=classification_metrics(outcomes, scores, saved_threshold(scored)),+ within_team=within_team_auc(outcomes, scores, team_ids),+ recency_within_team=within_team_auc(outcomes, newest_first, team_ids),))return gradesdiff --git a/products/signals/dags/inbox_ranking/training/within_team.py b/products/signals/dags/inbox_ranking/training/within_team.pynew file mode 100644index 000000000000..40667e886617--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/within_team.py@@ -0,0 +1,75 @@+"""AUC inside one team, for the inbox order.++The inbox sorts one team's reports, while a pooled AUC compares every report with every other.+A pooled AUC therefore rewards a model that knows which teams engage a lot, and that knowledge does+not change the order inside any inbox. A score equal to each team's past label rate gets a pooled+AUC well above 0.5 and a within-team AUC of exactly 0.5.++Only the pairs inside one team count here. `auc` weighs each team by its positive x negative pairs,+so it answers "how often does a positive report outrank a negative one in its own inbox". `macro`+weighs each team the same, so a few large teams cannot carry it.+"""++import numpy as np+import pandas as pd++from posthog.dataclasses import frozen+++@frozen+class WithinTeamAuc:+ # None when no team has both outcome classes, like the pooled AUC helpers.+ auc: float | None = None+ macro: float | None = None+ # The teams with both outcome classes, and their summed positive x negative pairs.+ teams: int = 0+ pairs: int = 0++ def as_dict(self, prefix: str = "") -> dict[str, int | float | None]:+ return {+ f"{prefix}within_team_auc": self.auc,+ f"{prefix}within_team_auc_macro": self.macro,+ f"{prefix}within_team_teams": self.teams,+ f"{prefix}within_team_pairs": self.pairs,+ }+++NO_TEAMS = WithinTeamAuc()+++def within_team_auc(outcomes: np.ndarray, scores: np.ndarray, team_ids: np.ndarray) -> WithinTeamAuc:+ """The Mann-Whitney U of each team, with ties paid 0.5, summed over the teams.++ A row without a team id is left out. A team with one outcome class has no pair and contributes+ nothing. A non-finite score makes the order undefined, so the result is NO_TEAMS, which is what+ the pooled AUC reports for the same rows.+ """+ rows = pd.DataFrame(+ {+ "team": pd.Series(team_ids, dtype=object),+ "outcome": np.asarray(outcomes, dtype=bool),+ "score": np.asarray(scores, dtype=float),+ }+ )+ rows = rows.loc[rows["team"].notna()].copy()+ if rows.empty or not np.isfinite(rows["score"].to_numpy()).all():+ return NO_TEAMS+ rank = rows.groupby("team")["score"].rank(method="average")+ rows["positive_rank"] = rank.where(rows["outcome"], 0.0)+ per_team = rows.groupby("team").agg(+ rows=("outcome", "size"),+ positives=("outcome", "sum"),+ positive_rank_sum=("positive_rank", "sum"),+ )+ per_team["negatives"] = per_team["rows"] - per_team["positives"]+ per_team = per_team[(per_team["positives"] > 0) & (per_team["negatives"] > 0)]+ if per_team.empty:+ return NO_TEAMS+ pairs = per_team["positives"] * per_team["negatives"]+ u = per_team["positive_rank_sum"] - per_team["positives"] * (per_team["positives"] + 1) / 2+ return WithinTeamAuc(+ auc=float(u.sum() / pairs.sum()),+ macro=float((u / pairs).mean()),+ teams=len(per_team),+ pairs=int(pairs.sum()),+ )