: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 an offline multi-head network prototype for inbox ranking (#115650)
posthog[bot]24e315b7c485
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 9d6f2b2a0667..2c924d956df4 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -15,6 +15,7 @@ inbox_ranking/│ ├── heads.py # the v0 outcome heads│ ├── train.py # per-head XGBoost fit + holdout/null metrics│ └── promotion.py # the champion promotion rule+├── multihead/ # dev-only: offline multi-head network prototype, no dag└── tests/```@@ -315,6 +316,22 @@ The training job is S3-only, so it can run on a laptop against copies of the proNothing here touches the prod bucket: the reader credential is read-only and the dag writes only to the local bucket.+### The multi-head prototype++`multihead/` is an offline experiment and not a dag. It tests whether one shared network over the report vector, with or without the team's project vectors, beats the per-head XGBoost champion recipe of the `report_embeddings` family. It reads the disk cache the sync script fills, so sync with `INBOX_RANKING_SYNC_EMBEDDINGS=1` first. The dev stack does not need to be up:++```bash+DEBUG=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:++- `champion_recipe` is the `XGB_PARAMS` booster, refit on the head's train rows.+- `nn_report` is the network over the report vector only.+- `nn_report_project` is the network over the report vector plus the `typical`, `open`, `action` and `dismiss` vectors from `project_vectors()`. A report born on day D reads them as of D 00:00 UTC.++The network leaves out every report that is in any head's holdout, so the comparison is conservative for it. A run holds one embeddings snapshot: the title embeddings are never read, and the project vectors are computed from the same table as the report vectors. Results vary with `--seed`, so compare a few seeds before you read a small AUC gap as a result.+## Configuration| Setting | Default | Meaning |diff --git a/products/signals/dags/inbox_ranking/multihead/__main__.py b/products/signals/dags/inbox_ranking/multihead/__main__.pynew file mode 100644index 000000000000..9d44dc866515--- /dev/null+++ b/products/signals/dags/inbox_ranking/multihead/__main__.py@@ -0,0 +1,53 @@+"""Run the multi-head prototype against the snapshots `bin/sync_snapshots_local.sh` cached on disk.++ INBOX_RANKING_SYNC_EMBEDDINGS=1 products/signals/dags/inbox_ranking/bin/sync_snapshots_local.sh+ DEBUG=1 python -m products.signals.dags.inbox_ranking.multihead [--partition YYYY-MM-DD] [--output results.json]++The cache must hold the state, labels and report embeddings tables. The title embeddings are never+read, so the run holds one set of vectors.+"""++import os+import argparse+from pathlib import Path++import django++DEFAULT_CACHE_DIR = Path(os.environ.get("INBOX_RANKING_SYNC_DIR", Path.home() / ".cache/posthog/inbox_ranking"))+++def _arguments() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--snapshots-dir", type=Path, default=DEFAULT_CACHE_DIR)+ parser.add_argument("--partition", help="the training day D; defaults to the newest day with every table cached")+ parser.add_argument("--lookback-days", type=int, help="defaults to INBOX_RANKING_TRAINING_LOOKBACK_DAYS")+ parser.add_argument("--holdout-days", type=int, help="defaults to INBOX_RANKING_TRAINING_HOLDOUT_DAYS")+ parser.add_argument("--ablation", choices=["report", "project", "both"], default="both")+ parser.add_argument("--skip-champion", action="store_true", help="skip the XGBoost champion recipe refit")+ parser.add_argument("--projection-dim", type=int, default=64)+ parser.add_argument("--trunk-dim", type=int, default=64)+ parser.add_argument("--dropout", type=float, default=0.2)+ parser.add_argument("--weight-decay", type=float, default=1e-2)+ parser.add_argument("--learning-rate", type=float, default=1e-3)+ parser.add_argument("--epochs", type=int, default=15)+ parser.add_argument("--batch-size", type=int, default=256)+ parser.add_argument("--seed", type=int, default=0)+ parser.add_argument("--output", type=Path, help="also write the scores as JSON here")+ return parser.parse_args()+++def main() -> None:+ arguments = _arguments()+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+ # The run reads only the disk cache. Without this, setup in DEBUG resolves a self-capture team+ # from Postgres, so the script would need the dev stack up.+ os.environ.setdefault("OPT_OUT_CAPTURE", "1")+ django.setup()+ # The dataset and training modules load Django models at import time, so they wait for setup.+ from products.signals.dags.inbox_ranking.multihead.local import run_from_cache # noqa: PLC0415++ run_from_cache(arguments)+++if __name__ == "__main__":+ main()diff --git a/products/signals/dags/inbox_ranking/multihead/local.py b/products/signals/dags/inbox_ranking/multihead/local.pynew file mode 100644index 000000000000..680a915bb934--- /dev/null+++ b/products/signals/dags/inbox_ranking/multihead/local.py@@ -0,0 +1,156 @@+"""Read the prototype's inputs from the disk cache `bin/sync_snapshots_local.sh` fills.++The cache mirrors the bucket layout below the prefix (`<table>/v1/dt=D/part-00000.parquet`), so+the training dag's own `load_snapshots` reads it through a store that answers `get_object` from disk.+"""++import io+import json+import argparse+import datetime+import dataclasses+from pathlib import Path+from typing import Any++import pyarrow as pa+import pyarrow.parquet as pq+from botocore.exceptions import ClientError++from posthog import settings++from products.signals.backend.ranking.features import (+ EMBEDDING_COLUMN,+ EMBEDDING_INSERTED_AT_COLUMN,+ REPORT_EMBEDDINGS_EXTRA,+ Extras,+)+from products.signals.dags.inbox_ranking.common import DATASET_VERSION, PARQUET_PART_NAME+from products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_TABLE, LABELS_TABLE, STATE_TABLE+from products.signals.dags.inbox_ranking.dataset.project_vectors import EMBEDDING_COLUMNS, LABEL_COLUMNS+from products.signals.dags.inbox_ranking.multihead.network import NetworkConfig+from products.signals.dags.inbox_ranking.multihead.prototype import (+ ABLATIONS,+ REPORT_ONLY,+ WITH_PROJECT_VECTORS,+ format_scores,+ run_prototype,+)+from products.signals.dags.inbox_ranking.training.dag import load_snapshots, snapshot_dates+from products.signals.dags.inbox_ranking.training.examples import Snapshot, drop_without_training_consent++_PREFIX = "local"+_TABLES = (STATE_TABLE, LABELS_TABLE, EMBEDDINGS_TABLE)+++class LocalSnapshotStore:+ """Answers the `get_object` calls of the dag's readers from the disk cache."""++ def __init__(self, root: Path) -> None:+ self.root = root++ def get_object(self, *, Bucket: str, Key: str) -> dict[str, Any]:+ path = self.root / Key.removeprefix(f"{_PREFIX}/")+ if not path.is_file():+ raise ClientError({"Error": {"Code": "NoSuchKey", "Message": str(path)}}, "GetObject")+ return {"Body": io.BytesIO(path.read_bytes())}+++def partition_path(root: Path, table: str, day: datetime.date) -> Path:+ return root / table / DATASET_VERSION / f"dt={day.isoformat()}" / PARQUET_PART_NAME+++def newest_cached_partition(root: Path) -> datetime.date:+ """The newest day for which the state, labels and report embeddings are all cached."""+ days: set[datetime.date] | None = None+ for table in _TABLES:+ present = {+ datetime.date.fromisoformat(path.parent.name.removeprefix("dt="))+ for path in (root / table / DATASET_VERSION).glob(f"dt=*/{PARQUET_PART_NAME}")+ }+ days = present if days is None else days & present+ if not days:+ raise SystemExit(+ f"no day in {root} has {', '.join(_TABLES)} cached; "+ "run bin/sync_snapshots_local.sh with INBOX_RANKING_SYNC_EMBEDDINGS=1"+ )+ return max(days)+++def consenting_snapshots(+ snapshots: dict[datetime.date, Snapshot], newest: datetime.date+) -> dict[datetime.date, Snapshot]:+ """`snapshots` without the reports of teams absent from the newest state snapshot.++ The training dag filters on `training_consent_team_ids()`, which reads the production database+ a local run cannot reach. The newest state snapshot holds only teams that allowed AI training on+ that day, so its teams stand in for the list and an opt-out still reaches older partitions.+ """+ state = snapshots[newest].state+ team_ids = frozenset(int(team_id) for team_id in state["report_team_id"].dropna())+ kept, _ = drop_without_training_consent(snapshots, team_ids)+ return kept+++def report_vectors(embeddings: pa.Table) -> Extras:+ """The `report_embeddings` side input, in the shape the dag's `embeddings_extras` builds."""+ vectors = (+ embeddings.select(["report_id", EMBEDDING_COLUMN, EMBEDDING_INSERTED_AT_COLUMN])+ .to_pandas()+ .set_index("report_id")+ )+ return {REPORT_EMBEDDINGS_EXTRA: vectors[~vectors.index.duplicated()]}+++def run_from_cache(arguments: argparse.Namespace) -> None:+ root: Path = arguments.snapshots_dir.expanduser()+ day = datetime.date.fromisoformat(arguments.partition) if arguments.partition else newest_cached_partition(root)+ lookback_days = arguments.lookback_days or settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS+ holdout_days = arguments.holdout_days or settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS+ ablations = {"report": (REPORT_ONLY,), "project": (WITH_PROJECT_VECTORS,), "both": ABLATIONS}[arguments.ablation]++ dates = snapshot_dates(day.isoformat(), lookback_days)+ snapshots = load_snapshots(LocalSnapshotStore(root), "", _PREFIX, dates, required=day)+ snapshots = consenting_snapshots(snapshots, day)+ print(f"dt={day}: {len(snapshots)} of {len(dates)} snapshots cached, holdout {holdout_days} days") # noqa: T201++ embeddings_path = partition_path(root, EMBEDDINGS_TABLE, day)+ if not embeddings_path.is_file():+ raise SystemExit(f"{embeddings_path} is missing; sync with INBOX_RANKING_SYNC_EMBEDDINGS=1")+ # One embeddings snapshot serves every moment, as in the training dag, and the project vectors+ # read the same table, so a single set of vectors is in memory.+ embeddings = pq.read_table(embeddings_path, columns=list(EMBEDDING_COLUMNS))+ labels = None+ if WITH_PROJECT_VECTORS in ablations:+ labels = pq.read_table(partition_path(root, LABELS_TABLE, day), columns=list(LABEL_COLUMNS))++ config = NetworkConfig(+ projection_dim=arguments.projection_dim,+ trunk_dim=arguments.trunk_dim,+ dropout=arguments.dropout,+ weight_decay=arguments.weight_decay,+ learning_rate=arguments.learning_rate,+ epochs=arguments.epochs,+ batch_size=arguments.batch_size,+ seed=arguments.seed,+ )+ result = run_prototype(+ snapshots,+ report_vectors(embeddings),+ labels=labels,+ embeddings=embeddings,+ holdout_days=holdout_days,+ config=config,+ ablations=ablations,+ champion=not arguments.skip_champion,+ )+ print(f"network train rows: {result.network_train_rows}") # noqa: T201+ print(format_scores(result.scores)) # noqa: T201+ if arguments.output:+ payload = {+ "partition": day.isoformat(),+ "lookback_days": lookback_days,+ "holdout_days": holdout_days,+ "config": dataclasses.asdict(config),+ **result.as_dict(),+ }+ arguments.output.write_text(json.dumps(payload, indent=2, default=str))diff --git a/products/signals/dags/inbox_ranking/multihead/network.py b/products/signals/dags/inbox_ranking/multihead/network.pynew file mode 100644index 000000000000..3283fd88d6b6--- /dev/null+++ b/products/signals/dags/inbox_ranking/multihead/network.py@@ -0,0 +1,244 @@+"""A multi-head network over a report's vector and, optionally, its team's project vectors.++ report vector ─┐+ ├─ shared Linear(1536 → k) ─ concat ─ dropout ─ trunk (ReLU) ─ dropout ─ one logit per head+ project vectors┘ (and report ⊙ project per kind, plus a history flag per kind)++One projection serves every vector, so the report and the team's history land in one learned space+and their element-wise product can say "this report looks like what the team engaged with". Weight+decay is decoupled (AdamW), and dropout sits on the trunk's input and output.++Plain numpy with a hand-written backward pass, because torch is not a main dependency and the+prototype has to run from the default environment. A gradient check test pins the backward pass.+A label is NaN where the head has no example for the row, and a NaN label adds no gradient.+"""++import math+from collections.abc import Iterator++import numpy as np++from posthog.dataclasses import frozen++from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS++# text-embedding-3 vectors are unit length, so each component is about 1/sqrt(D). Scaling by+# sqrt(D) gives the projection unit-variance inputs, which is what its initialization assumes.+INPUT_SCALE = math.sqrt(EMBEDDING_DIMENSIONS)+++@frozen+class NetworkConfig:+ projection_dim: int = 64+ trunk_dim: int = 64+ dropout: float = 0.2+ weight_decay: float = 1e-2+ learning_rate: float = 1e-3+ epochs: int = 15+ batch_size: int = 256+ seed: int = 0+++@frozen+class ProjectContext:+ """The team's project vectors per (team, moment), shared by every report of that pair."""++ # (pairs, kinds, D) float32; an all-zero row where the kind's history is too thin.+ vectors: np.ndarray+ # (pairs, kinds) float32, 1.0 where the kind had enough history to carry a mean.+ has_history: np.ndarray+ # (rows,) int, the pair each example row reads.+ index: np.ndarray+++@frozen+class NetworkInputs:+ # (rows, D) float32.+ reports: np.ndarray+ context: ProjectContext | None = None++ def __len__(self) -> int:+ return len(self.reports)+++@frozen(frozen=False)+class _Cache:+ """What the forward pass keeps for the backward pass of one batch."""++ reports: np.ndarray+ projected: np.ndarray+ context: np.ndarray | None+ projected_context: np.ndarray | None+ trunk_input: np.ndarray+ trunk_input_keep: np.ndarray | None+ trunk_pre: np.ndarray+ trunk_out: np.ndarray+ trunk_out_keep: np.ndarray | None+++class MultiHeadNetwork:+ def __init__(self, *, heads: int, with_context: bool, kinds: int, config: NetworkConfig) -> None:+ self.heads = heads+ self.with_context = with_context+ self.kinds = kinds if with_context else 0+ self.config = config+ self._rng = np.random.default_rng(config.seed)+ k, h = config.projection_dim, config.trunk_dim+ trunk_in = k + self.kinds * (2 * k + 1)+ self.params: dict[str, np.ndarray] = {+ "projection_w": self._glorot(EMBEDDING_DIMENSIONS, k),+ "projection_b": np.zeros(k, dtype=np.float32),+ "trunk_w": self._glorot(trunk_in, h),+ "trunk_b": np.zeros(h, dtype=np.float32),+ "heads_w": self._glorot(h, heads),+ "heads_b": np.zeros(heads, dtype=np.float32),+ }+ self._first_moment = {name: np.zeros_like(value) for name, value in self.params.items()}+ self._second_moment = {name: np.zeros_like(value) for name, value in self.params.items()}+ self._steps = 0++ def _glorot(self, fan_in: int, fan_out: int) -> np.ndarray:+ scale = math.sqrt(2.0 / (fan_in + fan_out))+ return self._rng.normal(0.0, scale, size=(fan_in, fan_out)).astype(np.float32)++ def _dropout_mask(self, shape: tuple[int, ...]) -> np.ndarray | None:+ rate = self.config.dropout+ if rate <= 0:+ return None+ return (self._rng.random(shape) >= rate).astype(np.float32) / (1.0 - rate)++ def _forward(self, inputs: NetworkInputs, rows: np.ndarray, *, train: bool) -> tuple[np.ndarray, _Cache]:+ p = self.params+ reports = inputs.reports[rows] * INPUT_SCALE+ projected = reports @ p["projection_w"] + p["projection_b"]+ parts = [projected]+ context = projected_context = None+ if self.with_context:+ if inputs.context is None:+ raise ValueError("a network built with context needs project vectors")+ pairs = inputs.context.index[rows]+ context = inputs.context.vectors[pairs] * INPUT_SCALE+ projected_context = context @ p["projection_w"] + p["projection_b"]+ batch = len(rows)+ parts += [+ projected_context.reshape(batch, -1),+ (projected[:, None, :] * projected_context).reshape(batch, -1),+ inputs.context.has_history[pairs],+ ]+ trunk_input = np.concatenate(parts, axis=1) if len(parts) > 1 else projected+ trunk_input_keep = self._dropout_mask(trunk_input.shape) if train else None+ dropped_input = trunk_input * trunk_input_keep if trunk_input_keep is not None else trunk_input+ trunk_pre = dropped_input @ p["trunk_w"] + p["trunk_b"]+ trunk_out = np.maximum(trunk_pre, 0.0)+ trunk_out_keep = self._dropout_mask(trunk_out.shape) if train else None+ dropped_out = trunk_out * trunk_out_keep if trunk_out_keep is not None else trunk_out+ logits = dropped_out @ p["heads_w"] + p["heads_b"]+ cache = _Cache(+ reports=reports,+ projected=projected,+ context=context,+ projected_context=projected_context,+ trunk_input=dropped_input,+ trunk_input_keep=trunk_input_keep,+ trunk_pre=trunk_pre,+ trunk_out=dropped_out,+ trunk_out_keep=trunk_out_keep,+ )+ return logits, cache++ def loss_and_gradients(+ self, inputs: NetworkInputs, labels: np.ndarray, rows: np.ndarray, *, train: bool = True+ ) -> tuple[float, dict[str, np.ndarray]]:+ """The mean binary cross-entropy over the observed labels of `rows`, and its gradients.++ Weight decay is not part of the loss, because AdamW applies it to the weights directly."""+ logits, cache = self._forward(inputs, rows, train=train)+ targets = labels[rows]+ observed = ~np.isnan(targets)+ count = max(int(observed.sum()), 1)+ filled = np.where(observed, targets, 0.0)+ # log(1 + exp(-|x|)) + max(x, 0) - x * y is the cross-entropy without overflow.+ losses = np.logaddexp(0.0, -np.abs(logits)) + np.maximum(logits, 0.0) - logits * filled+ loss = float((losses * observed).sum() / count)+ d_logits = (_sigmoid(logits) - filled) * observed / count+ return loss, self._backward(cache, d_logits)++ def _backward(self, cache: _Cache, d_logits: np.ndarray) -> dict[str, np.ndarray]:+ p = self.params+ k = self.config.projection_dim+ grads: dict[str, np.ndarray] = {+ "heads_w": cache.trunk_out.T @ d_logits,+ "heads_b": d_logits.sum(axis=0),+ }+ d_out = d_logits @ p["heads_w"].T+ if cache.trunk_out_keep is not None:+ d_out *= cache.trunk_out_keep+ d_pre = d_out * (cache.trunk_pre > 0)+ grads["trunk_w"] = cache.trunk_input.T @ d_pre+ grads["trunk_b"] = d_pre.sum(axis=0)+ d_input = d_pre @ p["trunk_w"].T+ if cache.trunk_input_keep is not None:+ d_input *= cache.trunk_input_keep++ d_projected = d_input[:, :k]+ grads["projection_w"] = cache.reports.T @ d_projected+ grads["projection_b"] = d_projected.sum(axis=0)+ if cache.projected_context is not None and cache.context is not None:+ batch, kinds = len(d_input), self.kinds+ offset = k + kinds * k+ d_context = d_input[:, k:offset].reshape(batch, kinds, k)+ d_product = d_input[:, offset : offset + kinds * k].reshape(batch, kinds, k)+ d_context = d_context + d_product * cache.projected[:, None, :]+ d_projected_from_product = (d_product * cache.projected_context).sum(axis=1)+ grads["projection_w"] += cache.reports.T @ d_projected_from_product+ grads["projection_b"] += d_projected_from_product.sum(axis=0)+ flat_context = cache.context.reshape(batch * kinds, -1)+ flat_d_context = d_context.reshape(batch * kinds, k)+ grads["projection_w"] += flat_context.T @ flat_d_context+ grads["projection_b"] += flat_d_context.sum(axis=0)+ return grads++ def _step(self, grads: dict[str, np.ndarray]) -> None:+ config = self.config+ beta1, beta2, epsilon = 0.9, 0.999, 1e-8+ self._steps += 1+ for name, grad in grads.items():+ self._first_moment[name] = beta1 * self._first_moment[name] + (1 - beta1) * grad+ self._second_moment[name] = beta2 * self._second_moment[name] + (1 - beta2) * grad * grad+ first = self._first_moment[name] / (1 - beta1**self._steps)+ second = self._second_moment[name] / (1 - beta2**self._steps)+ update = first / (np.sqrt(second) + epsilon)+ # Biases are not decayed: shrinking a head's bias pulls its base rate away from the label rate.+ if name.endswith("_w"):+ update = update + config.weight_decay * self.params[name]+ self.params[name] = (self.params[name] - config.learning_rate * update).astype(np.float32)++ def fit(self, inputs: NetworkInputs, labels: np.ndarray, rows: np.ndarray) -> list[float]:+ """Train on `rows` for the configured epochs; returns the mean loss per epoch."""+ history: list[float] = []+ for _ in range(self.config.epochs):+ losses = []+ for batch in self._batches(rows, shuffle=True):+ loss, grads = self.loss_and_gradients(inputs, labels, batch)+ self._step(grads)+ losses.append(loss)+ history.append(float(np.mean(losses)) if losses else float("nan"))+ return history++ def predict(self, inputs: NetworkInputs, rows: np.ndarray) -> np.ndarray:+ """(len(rows), heads) probabilities, without dropout."""+ if len(rows) == 0:+ return np.zeros((0, self.heads), dtype=np.float32)+ return np.concatenate(+ [_sigmoid(self._forward(inputs, batch, train=False)[0]) for batch in self._batches(rows, shuffle=False)]+ )++ def _batches(self, rows: np.ndarray, *, shuffle: bool) -> Iterator[np.ndarray]:+ order = self._rng.permutation(rows) if shuffle else rows+ size = self.config.batch_size+ for start in range(0, len(order), size):+ yield order[start : start + size]+++def _sigmoid(values: np.ndarray) -> np.ndarray:+ return np.exp(-np.logaddexp(0.0, -values))diff --git a/products/signals/dags/inbox_ranking/multihead/prototype.py b/products/signals/dags/inbox_ranking/multihead/prototype.pynew file mode 100644index 000000000000..349c1a678928--- /dev/null+++ b/products/signals/dags/inbox_ranking/multihead/prototype.py@@ -0,0 +1,299 @@+"""Offline test of one multi-head network against the per-head XGBoost champion recipe.++Dev only: nothing here is a dag, writes an object, or reaches serving. It answers one question+before anyone builds a new model family: does a shared network over the report vector, with or+without the team's project vectors, beat the `report_embeddings` boosters on the same rows?++The rows are the training dag's own. Each head's moments come from `example_moments` over the+`report_embeddings` set, capped by `cap_examples` and split by `holdout_mask`, so every head's+cohort, horizon, row budget and holdout are the ones its champion is graded on. The champion+recipe (`XGB_PARAMS`, one booster per head, fit on that head's train rows) is refit on the same+split rather than loaded, because a saved champion was fit on a window that can overlap this+holdout.++The network trains on one row per report with a label per head, NaN where the head has no example.+A report in any head's holdout is left out of the network's training rows for every head. Without+that rule a report in the `fixed` holdout (born three weeks ago) would train the shared trunk+through its `open` label, which is an outcome that serving cannot see at birth. The champion recipe+keeps those rows, so the comparison is conservative for the network.++Project vectors come from `project_vectors()` over the newest labels and embeddings snapshots. A+report born on day D reads the vectors as of D 00:00 UTC, the dt=D−1 vectors serving would read.+"""++import datetime+from collections.abc import Mapping, Sequence++import numpy as np+import pandas as pd+import pyarrow as pa+import xgboost as xgb+import pyarrow.compute as pc+from sklearn.metrics import average_precision_score, roc_auc_score++from posthog.dataclasses import frozen++from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS, REPORT_EMBEDDINGS_FEATURE_SET, Extras+from products.signals.dags.inbox_ranking.common import snapshot_bounds+from products.signals.dags.inbox_ranking.dataset.project_vectors import (+ MIN_HISTORY_REPORTS,+ VECTOR_KINDS,+ project_vectors,+)+from products.signals.dags.inbox_ranking.multihead.network import (+ MultiHeadNetwork,+ NetworkConfig,+ NetworkInputs,+ ProjectContext,+)+from products.signals.dags.inbox_ranking.training.calibration import calibration_buckets, expected_calibration_error+from products.signals.dags.inbox_ranking.training.examples import Snapshot, cap_examples, example_moments, holdout_mask+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head+from products.signals.dags.inbox_ranking.training.train import XGB_PARAMS++PROTOTYPE_HEADS: tuple[Head, ...] = tuple(HEADS_BY_NAME[name] for name in ("open", "action", "fixed"))+FEATURE_SET = REPORT_EMBEDDINGS_FEATURE_SET++CHAMPION_RECIPE = "champion_recipe"+REPORT_ONLY = "nn_report"+WITH_PROJECT_VECTORS = "nn_report_project"+ABLATIONS = (REPORT_ONLY, WITH_PROJECT_VECTORS)+++@frozen+class ExampleTable:+ """One row per report moment, with a label and a holdout flag per head in `PROTOTYPE_HEADS` order."""++ # report_id, snapshot_date, report_team_id.+ rows: pd.DataFrame+ # (rows, heads) float32, NaN where the head has no example for the row.+ labels: np.ndarray+ # (rows, heads) bool, the head's own `holdout_mask`.+ holdout: np.ndarray++ def network_train_rows(self) -> np.ndarray:+ """Rows with a label for some head and in no head's holdout."""+ observed = ~np.isnan(self.labels)+ return np.flatnonzero(observed.any(axis=1) & ~self.holdout.any(axis=1))++ def head_rows(self, head_index: int, *, holdout: bool) -> np.ndarray:+ observed = ~np.isnan(self.labels[:, head_index])+ in_holdout = self.holdout[:, head_index]+ return np.flatnonzero(observed & (in_holdout if holdout else ~in_holdout))+++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."""+ frames = []+ for head in PROTOTYPE_HEADS:+ moments = cap_examples(example_moments(snapshots, head, FEATURE_SET, extras), FEATURE_SET.max_examples_per_head)+ frames.append(+ moments.assign(holdout=holdout_mask(moments, holdout_days).to_numpy())+ .set_index(["report_id", "snapshot_date"])[["label", "holdout"]]+ .add_prefix(f"{head.name}:")+ )+ joined = pd.concat(frames, axis=1, join="outer").sort_index()+ rows = joined.index.to_frame(index=False)+ rows["report_team_id"] = [snapshots[date].state.at[report_id, "report_team_id"] for report_id, date in joined.index]+ labels = np.column_stack([joined[f"{head.name}:label"].to_numpy(dtype=np.float32) for head in PROTOTYPE_HEADS])+ holdout = np.column_stack([joined[f"{head.name}:holdout"].eq(True).to_numpy() for head in PROTOTYPE_HEADS])+ return ExampleTable(rows=rows, labels=labels, holdout=holdout)+++def report_matrix(rows: pd.DataFrame, extras: Extras) -> np.ndarray:+ """(rows, D) float32 report vectors, built by the set's own `build_matrix` at each row's moment,+ so a row carries the vector its champion example carries."""+ matrix = np.empty((len(rows), EMBEDDING_DIMENSIONS), dtype=np.float32)+ for date, group in rows.groupby("snapshot_date", sort=True):+ _, snapshot_end = snapshot_bounds(date.isoformat())+ frame = pd.DataFrame(index=pd.Index(group["report_id"], name="report_id"))+ matrix[group.index.to_numpy()] = FEATURE_SET.build_matrix(frame, extras, as_of=snapshot_end).to_numpy(+ dtype=np.float32+ )+ return matrix+++def project_context(rows: pd.DataFrame, labels: pa.Table, embeddings: pa.Table) -> ProjectContext:+ """The project vectors each row reads: its team's, as of the start of its snapshot day.++ One `project_vectors()` call per snapshot day, and only the needed teams' rows are kept from it,+ so the context holds a vector per (team, day) rather than one per example row.+ """+ kinds = len(VECTOR_KINDS)+ pair_keys = rows[["report_team_id", "snapshot_date"]].drop_duplicates().reset_index(drop=True)+ vectors = np.zeros((len(pair_keys), kinds, EMBEDDING_DIMENSIONS), dtype=np.float32)+ has_history = np.zeros((len(pair_keys), kinds), dtype=np.float32)+ pair_of: dict[tuple[int, datetime.date], int] = {}+ for date, group in pair_keys.groupby("snapshot_date", sort=True):+ as_of, _ = snapshot_bounds(date.isoformat())+ teams = {int(team_id): int(pair) for pair, team_id in group["report_team_id"].items()}+ pair_of.update({(team_id, date): pair for team_id, pair in teams.items()})+ day = project_vectors(labels, embeddings, as_of)+ day_vectors = (+ pc.list_flatten(day.column("vector").combine_chunks())+ .to_numpy(zero_copy_only=False)+ .reshape(-1, EMBEDDING_DIMENSIONS)+ )+ for position, (team_id, kind, n_reports) in enumerate(+ zip(+ day.column("team_id").to_numpy(),+ day.column("kind").to_pylist(),+ day.column("n_reports").to_numpy(),+ strict=True,+ )+ ):+ pair = teams.get(int(team_id))+ if pair is None:+ continue+ kind_index = VECTOR_KINDS.index(kind)+ vectors[pair, kind_index] = day_vectors[position]+ has_history[pair, kind_index] = float(int(n_reports) >= MIN_HISTORY_REPORTS)+ index = np.array(+ [pair_of[(int(team_id), date)] for team_id, date in zip(rows["report_team_id"], rows["snapshot_date"])],+ dtype=np.int64,+ )+ return ProjectContext(vectors=vectors, has_history=has_history, index=index)+++@frozen+class HeadScore:+ model: str+ head: str+ holdout_rows: int+ holdout_positives: int+ auc: float | None+ average_precision: float | None+ expected_calibration_error: float | None++ def as_dict(self) -> dict[str, object]:+ return {+ "model": self.model,+ "head": self.head,+ "holdout_rows": self.holdout_rows,+ "holdout_positives": self.holdout_positives,+ "auc": self.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."""+ positives = int(outcomes.sum())+ two_classes = 0 < positives < len(outcomes)+ return HeadScore(+ model=model,+ head=head,+ holdout_rows=len(outcomes),+ holdout_positives=positives,+ auc=float(roc_auc_score(outcomes, scores)) if two_classes else None,+ 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)),+ )+++def champion_recipe_scores(table: ExampleTable, reports: np.ndarray, *, seed: int) -> list[HeadScore]:+ """One `XGB_PARAMS` booster per head, fit on the head's train rows and graded on its holdout."""+ scores: list[HeadScore] = []+ for head_index, head in enumerate(PROTOTYPE_HEADS):+ train = table.head_rows(head_index, holdout=False)+ test = table.head_rows(head_index, holdout=True)+ y_train = table.labels[train, head_index].astype(int)+ y_test = table.labels[test, head_index].astype(int)+ if len(test) == 0 or y_train.sum() in (0, len(y_train)):+ continue+ model = 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]))+ return scores+++def network_scores(+ name: str, table: ExampleTable, inputs: NetworkInputs, config: NetworkConfig+) -> tuple[list[HeadScore], list[float]]:+ """Fit one network on the shared train rows and grade each head on its own holdout."""+ network = MultiHeadNetwork(+ heads=len(PROTOTYPE_HEADS),+ with_context=inputs.context is not None,+ kinds=len(VECTOR_KINDS),+ config=config,+ )+ losses = network.fit(inputs, table.labels, table.network_train_rows())+ scores: list[HeadScore] = []+ for head_index, head in enumerate(PROTOTYPE_HEADS):+ test = table.head_rows(head_index, holdout=True)+ if len(test) == 0:+ continue+ predicted = network.predict(inputs, test)[:, head_index]+ scores.append(grade(name, head.name, table.labels[test, head_index].astype(int), predicted))+ return scores, losses+++@frozen+class PrototypeResult:+ scores: tuple[HeadScore, ...]+ network_train_rows: int+ # Mean training loss per epoch, per network.+ losses: Mapping[str, Sequence[float]]++ def as_dict(self) -> dict[str, object]:+ return {+ "scores": [score.as_dict() for score in self.scores],+ "network_train_rows": self.network_train_rows,+ "losses": {name: list(values) for name, values in self.losses.items()},+ }+++def run_prototype(+ snapshots: Mapping[datetime.date, Snapshot],+ extras: Extras,+ *,+ labels: pa.Table | None,+ embeddings: pa.Table | None,+ holdout_days: int,+ config: NetworkConfig,+ ablations: Sequence[str] = ABLATIONS,+ champion: bool = True,+) -> PrototypeResult:+ """Every requested model graded per head on the champion's holdout rows.++ `labels` and `embeddings` are the newest labels and embeddings snapshots, needed only by the+ project-vector ablation. `extras` must be built from the same embeddings snapshot, so the run+ holds one set of vectors.+ """+ table = example_table(snapshots, extras, holdout_days=holdout_days)+ reports = report_matrix(table.rows, extras)+ scores: list[HeadScore] = []+ losses: dict[str, list[float]] = {}+ if champion:+ scores += champion_recipe_scores(table, reports, seed=config.seed)+ for ablation in ablations:+ context = None+ if ablation == WITH_PROJECT_VECTORS:+ if labels is None or embeddings is None:+ raise ValueError("the project-vector ablation needs the labels and embeddings snapshots")+ context = project_context(table.rows, labels, embeddings)+ head_scores, losses[ablation] = network_scores(+ ablation, table, NetworkInputs(reports=reports, context=context), config+ )+ scores += head_scores+ return PrototypeResult(scores=tuple(scores), network_train_rows=len(table.network_train_rows()), losses=losses)+++def format_scores(scores: Sequence[HeadScore]) -> str:+ """One line per (head, model), the champion recipe first within each head."""++ 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}"+ 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.expected_calibration_error):>8}"+ )+ return "\n".join(lines)diff --git a/products/signals/dags/inbox_ranking/tests/test_multihead.py b/products/signals/dags/inbox_ranking/tests/test_multihead.pynew file mode 100644index 000000000000..76206ec6d2ec--- /dev/null+++ b/products/signals/dags/inbox_ranking/tests/test_multihead.py@@ -0,0 +1,238 @@+import math+import datetime++import pytest++import numpy as np+import pandas as pd+import pyarrow as pa+from parameterized import parameterized++from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS+from products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_SCHEMA, LABELS_SCHEMA+from products.signals.dags.inbox_ranking.dataset.project_vectors import HISTORY_LIMIT, MIN_HISTORY_REPORTS, VECTOR_KINDS+from products.signals.dags.inbox_ranking.multihead.local import report_vectors+from products.signals.dags.inbox_ranking.multihead.network import (+ MultiHeadNetwork,+ NetworkConfig,+ NetworkInputs,+ ProjectContext,+)+from products.signals.dags.inbox_ranking.multihead.prototype import (+ ABLATIONS,+ CHAMPION_RECIPE,+ FEATURE_SET,+ PROTOTYPE_HEADS,+ example_table,+ project_context,+ run_prototype,+)+from products.signals.dags.inbox_ranking.training.examples import Snapshot, cap_examples, example_moments, holdout_mask+from products.signals.dags.inbox_ranking.training.heads import ACTION_LABEL_COLUMNS++D0 = datetime.date(2026, 8, 1)+DAYS = 40+REPORTS_PER_DAY = 12+HOLDOUT_DAYS = 7+TEAMS = (2, 3)+# One latent outcome per head, each written into its own component of the report vector, so a+# network that reads one head's output for another head ranks at chance.+HEAD_COMPONENTS = {"open": 0, "action": 1, "fixed": 2}+++def _birth(day: int) -> pd.Timestamp:+ birth = pd.Timestamp(datetime.datetime.combine(D0, datetime.time(12), tzinfo=datetime.UTC)) + pd.Timedelta(days=day)+ assert isinstance(birth, pd.Timestamp)+ return birth+++class _SyntheticInbox:+ def __init__(self, seed: int = 0) -> None:+ rng = np.random.default_rng(seed)+ self.reports = pd.DataFrame(+ [+ {+ "report_id": f"r-{day}-{index}",+ "born": day,+ "team": TEAMS[index % len(TEAMS)],+ **{head: bool(rng.random() < 0.4) for head in HEAD_COMPONENTS},+ }+ for day in range(DAYS)+ for index in range(REPORTS_PER_DAY)+ ]+ ).set_index("report_id")+ vectors = rng.normal(0.0, 0.3, size=(len(self.reports), EMBEDDING_DIMENSIONS))+ for head, component in HEAD_COMPONENTS.items():+ vectors[:, component] += np.where(self.reports[head], 3.0, -3.0)+ self.vectors = (vectors / np.linalg.norm(vectors, axis=1, keepdims=True)).astype(np.float32)++ def snapshots(self) -> dict[datetime.date, Snapshot]:+ snapshots: dict[datetime.date, Snapshot] = {}+ for day in range(DAYS):+ live = self.reports[self.reports["born"] <= day]+ state = pd.DataFrame(+ {+ "report_created_at": [_birth(born) for born in live["born"]],+ "report_age_hours": (day - live["born"]) * 24.0 + 12.0,+ "signal_count": 1,+ "report_team_id": live["team"],+ },+ index=live.index,+ )+ # Every outcome lands the day after the report is born, inside every head's horizon.+ visible = live["born"] < day+ labels = pd.DataFrame(+ {+ "open_count": (live["open"] & visible).astype(int),+ "fixed_count": (live["fixed"] & visible).astype(int),+ **dict.fromkeys(ACTION_LABEL_COLUMNS, 0),+ },+ index=live.index,+ )+ labels["claim_count"] = (live["action"] & visible).astype(int)+ date = D0 + datetime.timedelta(days=day)+ snapshots[date] = Snapshot(date=date, state=state, labels=labels)+ return snapshots++ def embeddings(self) -> pa.Table:+ return pa.Table.from_pylist(+ [+ {+ "snapshot_date": D0 + datetime.timedelta(days=DAYS - 1),+ "report_id": report_id,+ "report_team_id": int(row["team"]),+ "embedding_small": vector.tolist(),+ "embedding_inserted_at": _birth(int(row["born"])).to_pydatetime(),+ "embedding_rendering": "title_summary_v1",+ "is_tombstone": False,+ }+ for (report_id, row), vector in zip(self.reports.iterrows(), self.vectors, strict=True)+ ],+ schema=EMBEDDINGS_SCHEMA,+ )++ def labels(self) -> pa.Table:+ return pa.Table.from_pylist(+ [+ {+ "snapshot_date": D0 + datetime.timedelta(days=DAYS - 1),+ "report_id": report_id,+ "first_opened_at": (_birth(int(row["born"])) + pd.Timedelta(days=1)).to_pydatetime()+ if row["open"]+ else None,+ }+ for report_id, row in self.reports.iterrows()+ ],+ schema=LABELS_SCHEMA,+ )++[email protected]([("report_only", False), ("with_project_vectors", True)])+def test_backward_pass_matches_the_numerical_gradient(_name: str, with_context: bool) -> None:+ rng = np.random.default_rng(0)+ rows, kinds = 6, 2+ network = MultiHeadNetwork(+ heads=3,+ with_context=with_context,+ kinds=kinds,+ config=NetworkConfig(projection_dim=3, trunk_dim=4, dropout=0.0),+ )+ network.params = {name: value.astype(np.float64) for name, value in network.params.items()}+ scale = 1 / math.sqrt(EMBEDDING_DIMENSIONS)+ context = (+ ProjectContext(+ vectors=rng.normal(0.0, scale, size=(2, kinds, EMBEDDING_DIMENSIONS)),+ has_history=np.array([[1.0, 0.0], [1.0, 1.0]]),+ index=np.array([0, 1, 0, 1, 0, 1]),+ )+ if with_context+ else None+ )+ inputs = NetworkInputs(reports=rng.normal(0.0, scale, size=(rows, EMBEDDING_DIMENSIONS)), context=context)+ labels = rng.integers(0, 2, size=(rows, 3)).astype(np.float64)+ labels[0, 1] = labels[3, 2] = np.nan+ every_row = np.arange(rows)++ _, gradients = network.loss_and_gradients(inputs, labels, every_row, train=False)++ epsilon = 1e-6+ for name, value in network.params.items():+ for flat in rng.choice(value.size, size=min(6, value.size), replace=False):+ position = np.unravel_index(flat, value.shape)+ original = value[position]+ value[position] = original + epsilon+ plus, _ = network.loss_and_gradients(inputs, labels, every_row, train=False)+ value[position] = original - epsilon+ minus, _ = network.loss_and_gradients(inputs, labels, every_row, train=False)+ value[position] = original+ assert gradients[name][position] == pytest.approx((plus - minus) / (2 * epsilon), rel=1e-4, abs=1e-8)+++def test_example_table_keeps_each_champion_holdout_and_trains_the_network_on_none_of_them() -> None:+ inbox = _SyntheticInbox()+ snapshots = inbox.snapshots()+ extras = report_vectors(inbox.embeddings())++ table = example_table(snapshots, extras, holdout_days=HOLDOUT_DAYS)++ train_reports = set(table.rows["report_id"].iloc[table.network_train_rows()])+ any_holdout: set[str] = set()+ for index, head in enumerate(PROTOTYPE_HEADS):+ moments = cap_examples(example_moments(snapshots, head, FEATURE_SET, extras), FEATURE_SET.max_examples_per_head)+ champion_holdout = set(moments["report_id"][holdout_mask(moments, HOLDOUT_DAYS).to_numpy()])+ assert set(table.rows["report_id"].iloc[table.head_rows(index, holdout=True)]) == champion_holdout+ any_holdout |= champion_holdout+ # A fixed-head holdout report is a train row for open, which has the shorter horizon.+ assert any_holdout - set(table.rows["report_id"].iloc[table.head_rows(0, holdout=True)])+ assert train_reports+ assert not train_reports & any_holdout+++def test_project_context_reads_the_team_history_from_before_the_birth_day() -> None:+ inbox = _SyntheticInbox()+ birth_day = 20+ rows = pd.DataFrame(+ {+ "report_id": ["new-2", "new-3"],+ "snapshot_date": [D0 + datetime.timedelta(days=birth_day)] * 2,+ "report_team_id": [2, 3],+ }+ )++ context = project_context(rows, inbox.labels(), inbox.embeddings())++ open_kind = VECTOR_KINDS.index("open")+ for row, team in enumerate((2, 3)):+ # Opens land a day after birth, so a report born the day before `birth_day` is opened on+ # `birth_day` itself, after the 00:00 cut, and stays out of the mean.+ opened_before = inbox.reports[+ (inbox.reports["team"] == team) & inbox.reports["open"] & (inbox.reports["born"] < birth_day - 1)+ ]+ assert MIN_HISTORY_REPORTS <= len(opened_before) <= HISTORY_LIMIT+ positions = [inbox.reports.index.get_loc(report_id) for report_id in opened_before.index]+ expected = inbox.vectors[positions].mean(axis=0)+ pair = context.index[row]+ np.testing.assert_allclose(context.vectors[pair, open_kind], expected, atol=1e-6)+ assert context.has_history[pair, open_kind] == 1.0+++def test_every_model_is_graded_on_the_champion_holdout_rows_and_each_head_reads_its_own_output() -> None:+ inbox = _SyntheticInbox()+ embeddings = inbox.embeddings()++ result = run_prototype(+ inbox.snapshots(),+ report_vectors(embeddings),+ labels=inbox.labels(),+ embeddings=embeddings,+ holdout_days=HOLDOUT_DAYS,+ config=NetworkConfig(projection_dim=8, trunk_dim=8, dropout=0.1, epochs=40, batch_size=32),+ )++ for head in PROTOTYPE_HEADS:+ scores = {score.model: score for score in result.scores if score.head == head.name}+ assert set(scores) == {CHAMPION_RECIPE, *ABLATIONS}+ assert len({(score.holdout_rows, score.holdout_positives) for score in scores.values()}) == 1+ for ablation in ABLATIONS:+ auc = scores[ablation].auc+ assert auc is not None and auc > 0.75